Guilherme Costa
Guilherme Costa

Reputation: 22

Substring after last occurrence of a number? (JAVA)

I need to substring a text from the last occurrence of a number, for example:

if the input is: "Any Address, 182739 typeB" I want the output to be: "tybeB".

Upvotes: 0

Views: 277

Answers (1)

Elliott Frisch
Elliott Frisch

Reputation: 201429

Use a regular expression. Match anything, .*, until there are one or more digits, \\d+, followed by any amount of whitespace, \\s*, and then group the remaining characters (.+) - use that expression to replace everything with the captured group. Like,

String input = "Any Address, 182739 typeB";
System.out.println(input.replaceAll(".*\\d+\\s*(.+)", "$1"));

Outputs (as requested)

typeB

Upvotes: 4

Related Questions