我想对下面的字符串进行字符串拆分
String ToSplit = "(2*(sqrt 9))/5";
进入以下字符串数组:
String[] Splitted = {"(", "2", "*", "(", "sqrt", "9", ")", ")", "/", "5"};
如您所见,字符串 ToSplit 没有空格,我很难将单词“sqrt”从其余元素中拆分出来,因为它是一个完整的单词。我正在做:
String[] Splitted = ToSplit.split("");
单词“sqrt”被拆分为{“s”、“q”、“r”、“t”}(很明显),我希望将其拆分为整个单词,以便将字符串拆分为如上所示
如何将单词“sqrt”(作为 1 个元素)与其他单词分开?
提前致谢。
最佳答案
这是一个工作解决方案,它根据环顾四周进行拆分。请参阅下面的代码以获取解释。
String input = "(2*(sqrt 9))/5";
String[] parts = input.split("(?<=[^\\w\\s])(?=\\w)|(?<=\\w)(?=[^\\w\\s])|(?<=[^\\w\\s])(?=[^\\w\\s])|\\s+");
for (String part : parts) {
System.out.println(part);
}
(
2
*
(
sqrt
9
)
)
/
5
正则表达式交替中有四个术语,这是每个术语的作用:
(?<=[^\\w\\s])(?=\\w)
split if what precedes is neither a word character nor whitespace, AND
what follows is a word character
e.g. split (2 into ( and 2
(?<=\\w)(?=[^\\w\\s])
split if what precedes is a word character AND
what follows is neither a word character nor whitespace
e.g. split 9) into 9 and )
(?<=[^\\w\\s])(?=[^\\w\\s])
split between two non word/whitespace characters
e.g. split )/ into ) and /
\\s+
finally, also split and consume any amount of whitespace
as a separator between terms
e.g. sqrt 9 becomes sqrt and 9
关于java - 想要在 Java 中专门进行字符串拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55155166/