1

I have a String and a Regex.

the string will look like DH18

and I have my regex ([a-zA-Z]*)([0-9]*) which splits up the letters and the words

I only want the digits, so that which is contained in the second curly brackets. How do I go about referencing this.

I want a statement like

if ($1 == 18)
   blah;

3 Answers 3

6

You can use a non-capturing group or a lookbehind for the part that you do not want:

(?:[a-zA-Z]*)([0-9]*)  // Non-capturing group
(?<=[a-zA-Z]*)([0-9]*) // Lookbehind

Note that regex returns groups only as strings, even when the group represents a number. Therefore, the check $1 == 18 needs to use equals():

if (matcher.group(1).equals("18")) {
    ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

Why do you need a non-capturing group at all? Wouldn't [a-zA-Z]*([0-9]*) suffice?
@shyam I assume that the letters part needs to be present for a match to be valid, otherwise there's no need for the OP to mention it at all.
1

With ([a-zA-Z]*)([0-9]*) you have to pick $2 instead of $1 to get digits as $0 is the complete match, and capturing parts start from $1 .

if($2.equals("18"))

Comments

0
Pattern p = Pattern.compile("-?\\d+");
    Matcher m = p.matcher("DH18");
    while (m.find()) {
        System.out.println(m.group()); //will print 18
    }

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.