pineapplecakes
pineapplecakes

Reputation: 75

Regex + Java - how to capture trailing numbers and everything else

i'm trying to capture 2 things in a String "T3st12345"

I want to capture the trailing numbers ("12345") and also the name of the test "T3st".

This is what I have right now to match the trailing numbers with java's Matcher library:

Pattern pattern = Pattern.compile("([0-9]*$)");
Matcher matcher = pattern.matcher("T3st12345");

but it returns "no match found".

How can I make this work for the trailing numbers and how do I capture the name of the test as well?

Upvotes: 1

Views: 651

Answers (2)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626794

You may use the following regex:

Pattern pattern = Pattern.compile("(\\p{Alnum}+?)([0-9]*)");
Matcher matcher = pattern.matcher("T3st12345");
if (matcher.matches()) {
    System.out.println(matcher.group(1));
    System.out.println(matcher.group(2));
}

See the Java demo

The (\\p{Alnum}+?)([0-9]*) pattern is used in the .matches() method (to require a full string match) and matches and captures into Group 1 one or more alphanumeric chars, as few as possible (+? is a lazy quantifier), and captures into Group 2 any zero or more digits.

Note that \\p{Alnum} can be replaced with a more explicit [a-zA-Z0-9].

Upvotes: 2

anubhava
anubhava

Reputation: 785128

You can use this regex with 2 captured groups:

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

RegEx Demo

RegEx Breakup:

  • ^: Start
  • (.*?): Captured group #1 that matches zero of any character (lazy)
  • (\d+): Captured group #1 that matches one or more digits before End
  • $: End

Upvotes: 2

Related Questions