Reputation: 1019
Imagine these String:
String s = "firstpartie_FOO_lastpartieofthestring"
or
String s = "lllalal_FOOBBARR_lastpartieofthestringofthedead"
With regexp, i want to extract the string after the second "_".
I've tried this:
Pattern p = Pattern.compile("(?<=_[A-Z]*_)");
Matcher m = p.matcher("lllalal_FOOBBARR_lastpartieofthestringofthedead")
But how to finish the regexp to extract the string "lastpartieofthestringofthedead" ?
Upvotes: 0
Views: 175
Reputation: 1019
I've found this way:
Pattern p = Pattern.compile("_[A-Z]*_(.*)");
I progress in regex study hi hi hi ;-)
Explained:
...after an underscore followed by any number (use of star) of uppercase chars => [A-Z]*, followed by another underscore => _[A-Z]*_
... , capture all characters => (.*)
Find example here: https://ideone.com/S5WJMr
Upvotes: 0
Reputation: 626738
If you want to fix your approach, capture the rest of the string with a capturing group:
String s = "lllalal_FOOBBARR_lastpartieofthestringofthedead";
Pattern p = Pattern.compile("^[^_]*_[^_]*_(.*)", Pattern.DOTALL);
Matcher m = p.matcher(s);
if (m.find()) {
System.out.println(m.group(1));
}
// => lastpartieofthestringofthedead
See the Java demo
Here, ^[^_]*_[^_]*_(.*)
matches the start of string (^
), 0+ chars other than _
([^_]*
), _
, again 0+ chars other than _
and a _
, and then captures the rest of the string into Group 1 (with (.*)
).
Else, split into 3 parts with _
:
String s = "lllalal_FOOBBARR_lastpartieofthestring_of_thedead";
String[] res = s.split("_", 3);
if (res.length > 2) {
System.out.println(res[2]);
}
// => lastpartieofthestring_of_thedead
See another demo
Upvotes: 3
Reputation: 2465
Try this, it looks for any amount of characters followed by a _
then another amount of characters followed by _
and captures everything else:
.*_.*_(.*)
And an example on Regex101:
https://regex101.com/r/sfVyL2/1
Upvotes: 1