regular expression java

后端 未结 3 1136
失恋的感觉
失恋的感觉 2021-01-03 04:43

I am trying to Take the content between Input, my pattern is not doing the right thing please help.

below is the sudocode:

s=\"Input one Input Two In         


        
相关标签:
3条回答
  • 2021-01-03 05:12

    this does not work, because m.matches is true if and only if the whole string is matched by the expression. You could go two ways:

    1. Use s.split("Input") instead, it gives you an array of the substrings between occurences of "Input"
    2. Use Matcher.find() and Matcher.group(int). But be aware that your current expression will match everything after the first occurence of "Input", so you should change your expression.

    Greetings, Jost

    0 讨论(0)
  • 2021-01-03 05:18
    import java.util.regex.*;
    public class Regex {
    
        public static void main(String[] args) {
            String s="Input one Input Two Input Three"; 
            Pattern pat = Pattern.compile("(Input) (\\w+)"); 
            Matcher m = pat.matcher(s); 
    
             while( m.find() ) { 
             System.out.println( m.group(2) ); 
             }
        }
    }
    
    0 讨论(0)
  • 2021-01-03 05:23

    Use a lookahead for Input and use find in a loop, instead of matches:

    Pattern pattern = Pattern.compile("Input(.*?)(?=Input|$)");
    Matcher matcher = pattern.matcher(s);
    while (matcher.find()) {
       System.out.println(matcher.group(1));
    }
    

    See it working online: ideone

    But it's better to use split here:

    String[] result = s.split("Input");
    // You need to ignore the first element in result, because it is empty.
    

    See it working online: ideone

    0 讨论(0)
提交回复
热议问题