简体   繁体   中英

java regex to extract 'only' the single digit numbers from a string

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!

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM