如何使用正则表达式Java拆分此字符串
正如标题所说,我特别想拆分字符串,但我不知道在字符串中放入什么。拆分(“regex”) 假设我们有:如何使用正则表达式Java拆分此字符串,java,regex,split,Java,Regex,Split,正如标题所说,我特别想拆分字符串,但我不知道在字符串中放入什么。拆分(“regex”) 假设我们有: String s = "sum := A+B*( 99.1 +.44 444 1234+++)-sum/232.123459" 现在我想把它拆分成这样: String[] splitted = ["sum"; ":="; "A"; "+"; "B"; "*"; "("; "99.1"; "+"; ".44"; "444"; "1234"; "+"; "+"; "+"; ")"; "-"; "s
String s = "sum := A+B*( 99.1 +.44 444 1234+++)-sum/232.123459"
现在我想把它拆分成这样:
String[] splitted = ["sum"; ":="; "A"; "+"; "B"; "*"; "("; "99.1"; "+"; ".44"; "444"; "1234"; "+"; "+"; "+"; ")"; "-"; "sum"; "/"; "232.123459"]
所以,基本上我想按空格、单词、数学运算符、数字、括号、字母和数字来分割“.44”必须保持这种方式
你能帮我吗?
提前感谢不要使用split()
。使用find()
循环
String regex = "[0-9]+\\.?[0-9]*" + // Match number (e.g. 999 or 999.99)
"|\\.[0-9]+" + // Match number (e.g. .999)
"|[a-zA-Z]\\w*" + // Match identifier
"|:=" + // Match complex operator
"|\\S"; // Match other single non-space, incl. operators: +, -, *, /, (, )
试验
输出
[sum,:=,A,+,B,*,(,99.1,+,.44,444,1234,+,+,+,+,),-,sum,/,232.123459]
是的,您试过什么?尝试创建一个模式
,然后使用匹配器。改为查找。字符串中通常没有可用作分隔符的内容,因此在split
中查找和使用分隔符很困难。此外,对于表达式,您应该真正使用解析器,而不是regexp。
String s = "sum := A+B*( 99.1 +.44 444 1234+++)-sum/232.123459";
String[] splitted = Pattern.compile(regex).matcher(s).results()
.map(MatchResult::group).toArray(String[]::new);
System.out.println(Arrays.toString(splitted));