Extracting some pattern using regex

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

Answers (5)

sotondolphin
sotondolphin

Reputation: 223

try the regexp below, the sentence only contains alphanumeric and spaces

^\d+~\d+~\w+~[\w\s]+

Upvotes: 0

vks
vks

Reputation: 67968

.*~(.*)$

This simple regex should work for you.

See demo

Upvotes: 0

M-N
M-N

Reputation: 310

you should use ( ) to extract the output you want, for more details see here

Upvotes: 0

Duncan Jones
Duncan Jones

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

Maroun
Maroun

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

Related Questions