java regex quantifiers

后端 未结 6 2134
春和景丽
春和景丽 2021-01-12 08:00

I have a string like

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

I need a regex to give me th

相关标签:
6条回答
  • 2021-01-12 08:19

    Why don't you just match for number\\d+, query the match location, and do the String splitting yourself?

    0 讨论(0)
  • 2021-01-12 08:20

    because .* is a greedy pattern. use .*? instead of .*

    Pattern pattern = Pattern.compile("number\\d+(.*?)(number\\d+)");
    Matcher matcher = pattern.matcher(string);
    while(matcher.find();){
        out(matcher.group());
    }
    
    0 讨论(0)
  • 2021-01-12 08:21
    Pattern pattern = Pattern.compile("\\w+\\d(\\s\\w+)\1*");
    Matcher matcher = pattern.matcher(string);
    
    while (matcher.find()) {
        System.out.println(matcher.group());
    }
    
    0 讨论(0)
  • 2021-01-12 08:35

    (.*) part of your regex is greedy, therefore it eats everything from that point to the end of the string. Change to non-greedy variant: (.*)?

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

    0 讨论(0)
  • 2021-01-12 08:42

    If "foobar" is just an example and really you mean "any word" use the following pattern: (number\\d+)\s+(\\w+)

    0 讨论(0)
  • 2021-01-12 08:43

    So you want number (+ an integer) followed by anything until the next number (or end of string), right?

    Then you need to tell that to the regex engine:

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

    In your regex, the .* matched as much as it could - everything until the end of the string. Also, you made the second part (number\\d+)? part of the match itself.

    Explanation of my solution:

    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.
    
    0 讨论(0)
提交回复
热议问题