0

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 ~?

2
  • 4
    Why not just s.split("~")? Commented Sep 2, 2014 at 7:58
  • OR. Try this regex (?<=~)[^~]*$ Commented Sep 2, 2014 at 8:23

5 Answers 5

1

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];
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

0

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

Comments

0
.*~(.*)$

This simple regex should work for you.

See demo

Comments

0

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

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.