Question

Given an identifier foo consisting of letters, numbers, and underscores, I want to split the string on the last integer. Examples:

"hello" => "hello", ""
"hello0" => "hello", "0"
"hello001" => "hello", "001"
"h123ello123" => "h123ello", "123"

I imagine I could use a regular expression to pull out this information, but wasn't sure that was the cleanest approach (and if it is, what that expression would look like).

Was it helpful?

Solution 2

You can use this split

split("(?=\\d*$)",2);

It will split on place before zero or more digits (\\d) which have end of string $ after it (which means they are at the end of string).
Parameter 2 will limit size of result array to two elements preventing this regex from farther splitting in places I marked | below

hello0|0|1

so result will be hello 001.

DEMO

OTHER TIPS

Use this regex for your Pattern.matcher(string) method call:

^(.+?)(\d*)$

In Java:

Pattern p = Pattern.compile( "^(.+?)(\\d*)$" );

And then use matcher.group(1) and matcher.group(2) for your matches (after calling matcher.find())

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top