0

let's say I have a string.

String str = "Hello6 9World 2, Nic8e D7ay!";

Matcher match = Pattern.compile("\\d+").matcher(str);

the line above would give me 6, 9, 2, 8 and 7, which is perfect!

But if my string changes to..

String str = "Hello69World 2, Nic8e D7ay!";

note that the space between 6 and 9 is removed in this string.

and if I run..

Matcher match = Pattern.compile("\\d+").matcher(str);

it would give me 69, 2, 8 and 7.

my requirement is to extract the single digit numbers only. here, what I need is 2, 8, 7 and omit 69.

could you please help me to improve my regex? Thank you!

0

1 Answer 1

6

For each digit, you have to check if it is not followed or preceded by a digit

You can try this :

public static void main(String[] args) {
    String str = "Hello69World 2, Nic8e D7ay!";
    Pattern p = Pattern.compile("(?<!\\d)\\d(?!\\d)");
    Matcher m = p.matcher(str);
    while (m.find()) {
        System.out.println(m.group());
    }

    System.out.println("***********");

    str = "Hello6 9World 2, Nic8e D7ay!";
    m = p.matcher(str);
    while (m.find()) {
        System.out.println(m.group());
    }

}

O/P :

2
8
7
***********
6
9
2
8
7
Sign up to request clarification or add additional context in comments.

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.