[英]Java regex - overlapping matches
在以下代碼中:
public static void main(String[] args) {
List<String> allMatches = new ArrayList<String>();
Matcher m = Pattern.compile("\\d+\\D+\\d+").matcher("2abc3abc4abc5");
while (m.find()) {
allMatches.add(m.group());
}
String[] res = allMatches.toArray(new String[0]);
System.out.println(Arrays.toString(res));
}
結果是:
[2abc3, 4abc5]
我希望它是
[2abc3, 3abc4, 4abc5]
如何實現?
使匹配器嘗試從后一個\\d+
開始其下一次掃描。
Matcher m = Pattern.compile("\\d+\\D+(\\d+)").matcher("2abc3abc4abc5");
if (m.find()) {
do {
allMatches.add(m.group());
} while (m.find(m.start(1)));
}
不確定這在 Java 中是否可行,但在 PCRE 中您可以執行以下操作:
(?=(\\d+\\D+\\d+)).
解釋
該技術是在前瞻中使用匹配組,然后“吃掉”一個字符以繼續前進。
(?=
: 正向前瞻的開始
(
: 開始匹配組 1
\\d+
:匹配一個數字一次或多次\\D+
:匹配一個非數字字符一次或多次\\d+
:匹配一個數字一次或多次)
: 第 1 組結束)
: 前瞻結束.
: 匹配任何東西,這是為了“前進”。感謝Casimir et Hippolyte,它似乎真的可以在 Java 中工作。 您只需要添加反斜杠並顯示第一個捕獲組: (?=(\\\\d+\\\\D+\\\\d+)).
. 在www.regexplanet.com 上測試:
HamZa的上述解決方案在Java中完美運行。 如果你想在文本中找到特定的模式,你所要做的就是:
String regex = "\d+\D+\d+";
String updatedRegex = "(?=(" + regex + ")).";
regex
是您正在尋找的模式並且要重疊,您需要用(?=(" at the start and ")).
將其包圍(?=(" at the start and ")).
在末尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.