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