gpt4 book ai didi

java - Java中的正则表达式具有多个条件来提取算术运算符

转载 作者:太空宇宙 更新时间:2023-11-04 06:51:40 25 4
gpt4 key购买 nike

我是正则表达式语法的新手,在谷歌上挖掘一整天后,仍然无法在java中找到一个好的正则表达式来从字符串中提取我想要的东西......例如:我有一个

stringA = "-3.5 + 2 * 3 / 2"
stringB = "2 * 3 / 2 - 3.5";

我使用的正则表达式是

regex="[\\+\\-\\*\\/]", -->choose +,-,*,or / from the target;

通过这样做,我能够捕获字符串中的任何符号,包括负号。

但是,只有当负号 (-) 后面跟着空格时,我才会捕获它。

也就是说,我想要结果

string A as [ +, *, /], these three signs and stringB as [ *, / , -]

我意识到我只需要在正则表达式中添加另一个条件作为负号,例如

regex = "[\\+{\\-\\s}\\*\\/]"  ---> I want to choose same thing but with 
extra condition "-"sign has to follow by a whitespace.

方括号不起作用这样。有没有人可以指导我如何在原始正则表达式中添加另一个条件?或者编写一个新的正则表达式来满足需求?预先非常感谢您。

最佳答案

Chi,这可能是您正在寻找的简单正则表达式:

[+*/]|(?<=\s)-

它是如何工作的?

有一个交替|在中间,这是“匹配这个或匹配那个”的一种说法。

左边是字符类 [+*/]匹配一个 +、* 或/

字符

右侧是后视 (?<=\s)断言“前面有一个空白字符”,然后我们匹配一个减号。

如何使用?

List<String> matchList = new ArrayList<String>();
try {
Pattern regex = Pattern.compile("[+*/]|(?<=\\s)-");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
matchList.add(regexMatcher.group());
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}

如果您有兴趣,您可能想阅读regex lookaheads and lookbehinds .

如果您有任何问题,请告诉我。

关于java - Java中的正则表达式具有多个条件来提取算术运算符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23236561/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com