Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
java正则表达式提取';只有';字符串中的单个数字_Java_Regex - Fatal编程技术网

java正则表达式提取';只有';字符串中的单个数字

java正则表达式提取';只有';字符串中的单个数字,java,regex,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("

假设我有一根绳子

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


你能帮我改进一下正则表达式吗?谢谢大家!

对于每个数字,您必须检查其后面或前面是否有 数字

您可以尝试以下方法:

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());
    }

}

对于每个数字,您必须检查其后面或前面是否有 数字

您可以尝试以下方法:

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());
    }

}