问题
I have the following code :
Pattern pattern = Pattern.compile("\\d+(?:\\.\\d+)?(\\s\\d+(?:\\.\\d+)?)*\\s*[-\\+\\*/\\$£]");
String input = "4.0 5.0 2.0 / + 7.0 - 11.0 34.0 2.0 / 3.0 / 1.0 * +";
Matcher matcher = pattern.matcher(input);
List<String> output = new ArrayList<>();
while (matcher.find()) {
output.add(matcher.group());
}
The pattern that is compiled has gone through a number of iterations, in it's current iteration it adds to the list the following :
[4.0 5.0 2.0 /, 7.0 -, 11.0 34.0 2.0 /, 3.0 /, 1.0 *]
It should be splitting by all operations and keeping the operations in the split string so i would have expected the following output:
[4.0 5.0 2.0 /,+, 7.0 -, 11.0 34.0 2.0 /, 3.0 /, 1.0 *, +]
It looks to be that is not splitting when it only finds an operator and not a number.
So essentially i would like the current behaviour as well as it splitting operators such that if it finds 2 operators in a row it splits them up. such that the following:
2 2 + / 3 +
would equal
[2 2 +, /, 3 +]
回答1:
You can use this regex:
((?:\d+(?:\.\d+)?(?:\s+\d+(?:\.\d+)?)*)?\s*[-+*/$£])
RegEx Demo
In Java it would be:
Pattern pattern = Pattern.compile
( "((?:\\d+(?:\\.\\d+)?(?:\\s+\\d+(?:\\.\\d+)?)*)?\\s*[-+*/$£])" );
回答2:
Maybe I am missing something, but from what you describe, I don't see why it needs to be so complicated. "[\\d. ]+?[-+/*£$]"
seems to do exactly what you want.
来源:https://stackoverflow.com/questions/27604625/pattern-is-not-splitting-as-desired-fails-to-split-by