Java pattern repeated Capturing Groups
-
15-11-2019 - |
Question
I have the following String
52x10x20x30x40
The string can be extended but with the same pattern and there will be other strings on both sides of it: for example
"Hello something 52x10x20x30x40 bla bla bla"
i want to capture all 2-digits.
I have the following regex
Pattern.compile("(\\d\\d)([x]\\d\\d)+");
But with this regex i only get the following groups:
1: 52
2: x40
Solution
Why not simply:
"52x10x20x30x40".split("x");
?
Forgot to mention that there can be other strings on both sides.
You could search for "\\d{2}(x\\d{2})+"
, and use split("x")
on the match.
OTHER TIPS
Regex doesn't support variable group lengths.
Use a split method instead, e.g. Guava's Splitter
:
Iterable<String> tokens = Splitter.on('x').split(str);
If you just want to capture all two digit numbers you could use this expression:
(?<!\d)(\d\d)(?!\d)
Usually you can only get the last substring that a repeated capturing group matches. (.NET regex differs in this regard.)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow