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 ~?
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];
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
s.split("~")?(?<=~)[^~]*$