简体   繁体   English

Java正则表达式从字符串中提取“仅”一位数字

[英]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! 上面的代码行会给我6、9、2、8和7,非常完美!

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. 请注意,此字符串中删除了6到9之间的空格。

and if I run.. 如果我跑..

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

it would give me 69, 2, 8 and 7. 它会给我69、2、8和7。

my requirement is to extract the single digit numbers only. 我的要求是仅提取一位数字。 here, what I need is 2, 8, 7 and omit 69. 在这里,我需要的是2、8、7并省略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 : O / P:

2
8
7
***********
6
9
2
8
7

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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