Java regular expression

I'm trying to take content between Input, my template is not doing the right thing, please help.

below is sudocode:

s="Input one Input Two Input Three"; Pattern pat = Pattern.compile("Input(.*?)"); Matcher m = pat.matcher(s); if m.matches(): print m.group(..) 

Required Conclusion:

one

Two

Three

+4
source share
3 answers

Use 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 how it works on the Internet: ideone

But it is better to use split here:

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

See how it works on the Internet: ideone

+11
source

this does not work because m.matches is true if and only if the entire string matches the expression. You can go in two ways:

  • Use s.split (β€œInput”) instead, it gives an array of substrings between occurrences of β€œInput”
  • Use Matcher.find () and Matcher.group (int). But keep in mind that your current expression will match everything after the first appearance of "Input", so you must change your expression.

Hi Jost

+2
source
 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
source

Source: https://habr.com/ru/post/1380944/


All Articles