Java regex question

I have text similar to

ab1ab2ab3ab4cd 

Is it possible to create a java regular expression to get all subtypes starting with "ab" and ending with "cd" ? eg:

 ab1ab2ab3ab4cd ab2ab3ab4cd ab3ab4cd ab4cd 

thanks

+4
source share
3 answers

The regular expression (?=(ab.*cd)) will group such matches in group 1, as you can see:

 import java.util.regex.*; public class Main { public static void main(String[] args) throws Exception { Matcher m = Pattern.compile("(?=(ab.*cd))").matcher("ab1ab2ab3ab4cd"); while (m.find()) { System.out.println(m.group(1)); } } } 

which produces:

 ab1ab2ab3ab4cd ab2ab3ab4cd ab3ab4cd ab4cd 

You need to look ahead, (?= ... ) , otherwise you will get only one match. Please note that the regular expression will not give the desired results if your line contains more than 2 cd . In this case, you will have to resort to some manual string algorithm.

+4
source

It looks like you want either ab\w+?cd or \bab\w+?cd\b

+1
source
 /^ab[a-z0-9]+cd$/gm 

If only a b c and digits 0-9 tags can appear in the middle, as in the examples:

 /^ab[ac\d]+cd$/gm 

See in action: http://regexr.com?2tpdu

0
source

All Articles