자바 패턴 반복 그룹 캡처 그룹
-
15-11-2019 - |
문제
다음 문자열이 있습니다
52x10x20x30x40
.
문자열을 확장 할 수 있지만 동일한 패턴으로 양쪽에 다른 문자열이 있습니다. 예를 들어
"Hello something 52x10x20x30x40 bla bla bla"
.
모든 2 자리를 캡처하고 싶습니다.
나는 다음과 같은 정규복
Pattern.compile("(\\d\\d)([x]\\d\\d)+");
.
그러나이 정규식을 사용하면 다음 그룹 만 얻습니다.
1: 52
2: x40
. 해결책
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.
다른 팁
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.)
제휴하지 않습니다 StackOverflow