如何替换多个匹配的正则表达式 [英] how to replace multiple matched Regex
问题描述
我有一组需要应用于一组String的正则表达式替换,
I have a set of regex replacements that are needed to be applied to a set of String,
例如:
- 单个空格的所有多个空格
(\\\ {2,} - >)
- 全部。然后是一个char。其次是空格,后跟字符
(\。([a-zA-Z] - >。$ 1)
- all multiple spaces with single space
("\s{2,}" --> " ")
- all . followed by a char with . followed by space followed by the char
(\.([a-zA-Z]-->". $1")
所以我会这样:
String s="hello .how are you?";
s=s.replaceAll("\\s{2,}"," ");
s=s.replaceAll("\\.([a-zA-Z])",". $1");
....
它有效,但想象一下,我试图在长字符串上替换100多个这样的表达式。不用说这有多慢。
it works , however imagine I'm trying to replace 100+ such expressions on a long String. needless to say how slow this can be.
所以我的问题是如果有一种更有效的方法来使用单个replaceAll(或类似的东西,例如Pattern / Matcher)来推广这些替换
so my question is if there is a more efficient way to generalize these replacements with a single replaceAll (or something similar e.g. Pattern/Matcher)
我已经跟随Java替换多个不同的...... ,
但问题是我的正则表达式不是简单的字符串
。
but the problem is that my regex(s) are not simple Strings
.
推荐答案
你有这2个 replaceAll
来电:
s = s.replaceAll("\\s{2,}"," ");
s = s.replaceAll("\\.([a-zA-Z])",". $1");
您可以将它们合并为一个 replaceAll
像这样:
You can combine them into a single replaceAll
like this:
s = s.replaceAll("\\s{2,}|(\\.)(?=[a-zA-Z])", "$1 ");
这篇关于如何替换多个匹配的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!