在正则表达式之外替换单词

huangapple go评论59阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2020年8月28日 12:21:02
  • 转载请务必保留本文链接:https://go.coder-hub.com/63627425.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定