如何解决使用 replaceAll() 在字符串中查找三位数
类似于:“我有 100 个朋友和 1 个邪恶”。
我需要仅使用 String
函数和适当的 replaceAll
从该 regex
中提取“100”。
我试图这样做:
String input = "I have 100 friends and 1 evil";
String result = input.replaceAll("[^\\d{3}]","")
但它不起作用。任何帮助将不胜感激。
解决方法
您可以考虑以下任何一种解决方案:
String result = input.replaceFirst(".*?(\\d{3}).*","$1");
String result = input.replaceFirst(".*?(?<!\\d)(\\d{3})(?!\\d).*","$1");
String result = input.replaceFirst(".*?\\b(\\d{3})\\b.*","$1");
String result = input.replaceFirst(".*?(?<!\\S)(\\d{3})(?!\\S).*","$1");
参见regex demo。 注意您也可以在此处使用 replaceAll
,但没有意义,因为在这种情况下替换必须只发生一次。
这里,
-
.*?
- 匹配除换行符以外的任何零个或多个字符,尽可能少 -
(\d{3})
- 将任意三位数字捕获到第 1 组中 -
.*
- 尽可能多地匹配除换行符以外的任何零个或多个字符。
(?<!\d)
/ (?!\d)
环视是数字边界,如果序列是四位或更多位,则不匹配。 \b
是单词边界,不会有匹配的三个数字粘在字母、数字或下划线上。 (?<!\S)
/ (?!\S)
环视是空白边界,匹配之前必须有空格或字符串开头,匹配之后必须有空格或字符串结尾。
替换为 $1
,即 Group 1 的值。
String input = "I have 100 friends and 1 evil";
System.out.println(input.replaceFirst(".*?(\\d{3}).*","$1"));
System.out.println(input.replaceFirst(".*?(?<!\\d)(\\d{3})(?!\\d).*","$1"));
System.out.println(input.replaceFirst(".*?\\b(\\d{3})\\b.*","$1"));
System.out.println(input.replaceFirst(".*?(?<!\\S)(\\d{3})(?!\\S).*","$1"));
所有输出100
。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。