簡體   English   中英

java正則表達式量詞

[英]java regex quantifiers

我有一個字符串

String string = "number0 foobar number1 foofoo number2 bar bar bar bar number3 foobar";

我需要一個正則表達式給我以下輸出:

number0 foobar
number1 foofoo
number2 bar bar bar bar
number3 foobar

我試過了

Pattern pattern = Pattern.compile("number\\d+(.*)(number\\d+)?");
Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
    System.out.println(matcher.group());
}

但這給了

number0 foobar number1 foofoo number2 bar bar bar bar number3 foobar

所以你想要number (+一個整數)后跟任何東西,直到下一個number (或字符串的結尾),對嗎?

然后你需要告訴正則表達式引擎:

Pattern pattern = Pattern.compile("number\\d+(?:(?!number).)*");

在你的正則表達式中, .*盡可能多地匹配 - 直到字符串結尾的所有內容。 另外,你做了第二部分(number\\\\d+)? 比賽本身的一部分。

解釋我的解決方案:

number    # Match "number"
\d+       # Match one of more digits
(?:       # Match...
 (?!      #  (as long as we're not right at the start of the text
  number  #   "number"
 )        #  )
 .        # any character
)*        # Repeat as needed.
Pattern pattern = Pattern.compile("\\w+\\d(\\s\\w+)\1*");
Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println(matcher.group());
}

因為.*是一種貪婪的模式。 使用.*? 而不是.*

Pattern pattern = Pattern.compile("number\\d+(.*?)(number\\d+)");
Matcher matcher = pattern.matcher(string);
while(matcher.find();){
    out(matcher.group());
}

如果“foobar”只是一個例子而且你的意思是“任何單詞”使用以下模式:( (number\\\\d+)\\s+(\\\\w+)

為什么不匹配number\\\\d+ ,查詢匹配位置,自己進行字符串拆分?

(.*)正則表達式的一部分是貪婪的,因此它會吃掉從該點到字符串末尾的所有內容。 改為非貪婪的變種: (.*)?

http://docs.oracle.com/javase/tutorial/essential/regex/quant.html

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM