Reputation: 1
I'm trying to write a regex pattern that will match a "digit~digit~string~sentence". eg 14~742091~065M998~P E ROUX 214
. I've come up with the following so far:
String regex= "\\d+~?\\d+~?\\w+~?"
How do I extract the sentence after the last ~
?
Upvotes: 0
Views: 68
Reputation: 223
try the regexp below, the sentence only contains alphanumeric and spaces
^\d+~\d+~\w+~[\w\s]+
Upvotes: 0
Reputation: 310
you should use ( )
to extract the output you want,
for more details see here
Upvotes: 0
Reputation: 69339
Use capturing groups ()
, as demonstrated in this pattern: "\\d+~\\d+~\\w+~(.*)"
. Note that you don't need the greedy quantifier ?
.
String input = "14~742091~065M998~P E ROUX 214";
Pattern pattern = Pattern.compile("\\d+~\\d+~\\w+~(.*)");
//Pattern pattern = Pattern.compile("(?:\\d+~){2}\\w+~(.*)"); (would also work)
Matcher matcher = pattern.matcher(input);
if (matcher.matches()) {
System.out.println(matcher.group(1));
}
Prints:
P E ROUX 214
Upvotes: 0
Reputation: 95968
Use Capturing Groups:
\d+~?\d+~?\w+~(.*)
group(1)
contains the part you want.
Another solution is using String#split
:
String[] splitted = myString.split("~");
String res = splitted[splitted.length() - 1];
Upvotes: 1