Regex Overlap

I found a similar question here . However, I did not get the job:

I have a string like "my_token_string" and you need a regular expression to return the tokens "my_", "_token_" and "_string".

Please note that I cannot change java code because it is part of other software. The only thing I can do is to specify the template and group to capture :-)

This is what I tested:

String p = "(?=(_[^_]*_?))"; int group = 1; String test = "my_token_string"; Matcher m = Pattern.compile(p).matcher(test); while (m.find()) { System.out.println(m.group(group)); } 

But, of course, this only returns the _token_ and _string tokens.

+4
source share
2 answers

You can try with "(?=((^|_).+?(_|$)))" . Use 1 as the group number.

It will start the token with _ or the beginning of input ( ^ ) and end it with _ or the end of input ( $ ). Instead .+? you can use [^_]+ , but I prefer this version.

+4
source

You can achieve this with RegEx: (?=((?:_|^)[^_]*+(?:_|$)))
Clarification demo: http://regex101.com/r/tB0bZ4

+3
source

All Articles