java regex从字符串

时间:2018-02-23 08:30:21

标签: java regex

假设我有一个字符串。

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

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

上面的行会给我6,9,2,8和7,这是完美的!

但如果我的字符串改为..

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

请注意,此字符串中将删除6到9之间的空格。

如果我跑...

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

它会给我69,2,8和7。

我的要求是仅提取单个数字。在这里,我需要的是2,8,7和省略69。

你可以帮助我改善我的正则表达式吗?谢谢!

1 个答案:

答案 0 :(得分:6)

对于每个数字,您必须检查是否未遵循或先于a  数字

你可以试试这个:

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
相关问题