gpt4 book ai didi

java - 使用正则表达式分割数字和表达式

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

我正在开发一个项目,我可以接受用户的字符串,用户可以在一行中输入负正值。

然后我使用正则表达式将其拆分为空格。我现在需要能够“修复”数组以包含数字和运算符。

  "(?<=[\\(\\)\\+\\-*\\/\\^A-Za-z])|(?=[\\(\\)\\+\\-*\\/\\^A-Za-z])"

例如,用户可以输入-1/2 - 1/2

我现在需要的元素是这样的arr[1] = -1arr[2] = 2 (或者/也可以)

目前是这样的:

-

1

/

2

-

1

/

2

我开始编写类似于 if arr[i].equals("-") 的案例,然后也获取下一个数字。好吧,这行不通,因为他们可以在中间有一个 - 。

任何想法都会受到赞赏。

最佳答案

我猜也许,一些类似于的表达

-?\s*[0-9.]+|([+÷*-])

如果之后进行验证,那么开始可能没问题。

不过,您在此处尝试完成的任务可能存在一些设计问题。

Demo

测试

import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class re{

public static void main(String[] args){

final String regex = "-?\\s*[0-9.]+|([+÷*-])";
final String string = "-1 /2 - 1/2.4\n"
+ "-1 /25 -- 1/23.2\n"
+ "-1 / 29 - 1/212.42\n"
+ "-1 / 2 - -1/2\n"
+ "-1 / 2 * -1/2\n"
+ "-1 / 2 + -1/2\n"
+ "-1 / 2 ÷ -1/2";

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}

}
}

输出

Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: - 1
Group 1: null
Full match: 2.4
Group 1: null
Full match: -1
Group 1: null
Full match: 25
Group 1: null
Full match: -
Group 1: -
Full match: - 1
Group 1: null
Full match: 23.2
Group 1: null
Full match: -1
Group 1: null
Full match: 29
Group 1: null
Full match: - 1
Group 1: null
Full match: 212.42
Group 1: null
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: -
Group 1: -
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: *
Group 1: *
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: +
Group 1: +
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: -1
Group 1: null
Full match: 2
Group 1: null
Full match: ÷
Group 1: ÷
Full match: -1
Group 1: null
Full match: 2
Group 1: null
<小时/>

如果您想探索/简化/修改表达式,它已经右上方面板上有解释 regex101.com 。如果你愿意的话,你也可以在thislink观看,它将如何匹配针对一些示例输入。

<小时/>

关于java - 使用正则表达式分割数字和表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57915908/

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