英文:
Replace word outside regex
问题
可以在反向方式下进行替换吗,其中正则表达式保持不变,而其他字符被消除?
Word
String word = "Lorem ipsum dolor sit amet, 27/08/2020 consectetur adipiscing elit. Etiam consequat nisi est.";
Regex
([0-9]{2}/[0-9]{2}/[0-9]{4})
word.replaceAll("([0-9]{2}/[0-9]{2}/[0-9]{4})","");
Expected
27/08/2020
英文:
Is it possible to make a replacement in an inverted way, where the regular expression is maintained and the other characters are eliminated?
Word
String word = "Lorem ipsum dolor sit amet, 27/08/2020 consectetur adipiscing elit. Etiam consequat nisi est.";
Regex
([0-9]{2}/[0-9]{2}/[0-9]{4})
word.replaceAll("([0-9]{2}/[0-9]{2}/[0-9]{4})","");
Expected
27/08/2020
答案1
得分: 1
是的,它被称为 find()
。
String word = "Lorem ipsum dolor sit amet, 27/08/2020 consectetur adipiscing elit. Etiam consequat nisi est.";
Matcher m = Pattern.compile("([0-9]{2}/[0-9]{2}/[0-9]{4})").matcher(word);
if (m.find())
System.out.println(m.group());
输出
27/08/2020
或者,使正则表达式匹配整个字符串,并使用您已定义的捕获组:
word.replaceFirst(".*?([0-9]{2}/[0-9]{2}/[0-9]{4}).*", "$1")
结果
27/08/2020
这两种方法的主要区别在于如果正则表达式不匹配,即字符串中没有日期时会发生什么。
第一种方法不会打印任何内容。您可以通过编写一个 else
子句来明确控制处理方式。
第二种方法将导致完整的原始字符串保持不变。您无法控制如何处理“未找到”条件。
英文:
Yes, it's called find()
.
String word = "Lorem ipsum dolor sit amet, 27/08/2020 consectetur adipiscing elit. Etiam consequat nisi est.";
Matcher m = Pattern.compile("([0-9]{2}/[0-9]{2}/[0-9]{4})").matcher(word);
if (m.find())
System.out.println(m.group());
Output
27/08/2020
Alternative, make the regex match everything, and use the capture group you already defined:
word.replaceFirst(".*?([0-9]{2}/[0-9]{2}/[0-9]{4}).*", "$1")
Result
27/08/2020
The main difference between the two if what happens of the regex doesn't match, i.e. if the string doesn't have a date in it.
The first will print nothing. You can explicitly control how you handle it by writing an else
clause.
The second will result in the full original string, unchanged. You cannot control how you handle the "not found" condition.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论