我希望用一个空格替换多于一个空格的任何出现,但不要在引号之间的文本中采取任何操作。正则表达式问题 - 引号之外的一个或多个空格包含的文本块
有没有办法用Java正则表达式来做这件事?如果是这样,你可以尝试它还是给我一个提示?
我希望用一个空格替换多于一个空格的任何出现,但不要在引号之间的文本中采取任何操作。正则表达式问题 - 引号之外的一个或多个空格包含的文本块
有没有办法用Java正则表达式来做这件事?如果是这样,你可以尝试它还是给我一个提示?
这里的另一种方法,使用一个超前来确定当前位置进来配对毕竟引号。
text = text.replaceAll(" ++(?=(?:[^\"]*+\"[^\"]*+\")*+[^\"]*+$)", " ");
如果需要,可以调整lookahead以处理引用段内的转义引号。
引号之间的文本:是在同一行还是多行内引号?
当试图匹配的东西,可以包含别的东西中,它可以帮助构建一个同时匹配正则表达式,像这样:
("[^"\\]*(?:\\.[^"\\]*)*")|( +)
这将匹配带引号的字符串或两个以上空间。由于这两个表达式组合在一起,它将匹配一个带引号的字符串或两个或多个空格,但引号内不包含空格。使用这个表情,你就需要检查每场比赛以确定它是否是带引号的字符串或两个以上的空间和采取相应的行动:
Pattern spaceOrStringRegex = Pattern.compile("(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")|( +)");
StringBuffer replacementBuffer = new StringBuffer();
Matcher spaceOrStringMatcher = spaceOrStringRegex.matcher(text);
while (spaceOrStringMatcher.find())
{
// if the space group is the match
if (spaceOrStringMatcher.group(2) != null)
{
// replace with a single space
spaceOrStringMatcher.appendReplacement(replacementBuffer, " ");
}
}
spaceOrStringMatcher.appendTail(replacementBuffer);
就个人而言,我不使用Java,但是这正则表达式可以做的伎俩:
([^\" ])*(\\\".*?\\\")*
试图与使用RegexBuddy的表达,它生成此代码,看起来好像没什么问题:
try {
Pattern regex = Pattern.compile("([^\" ])*(\\\".*?\\\")*", Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE);
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
for (int i = 1; i <= regexMatcher.groupCount(); i++) {
// matched text: regexMatcher.group(i)
// match start: regexMatcher.start(i)
// match end: regexMatcher.end(i)
// I suppose here you must use something like
// sstr += regexMatcher.group(i) + " "
}
}
} catch (PatternSyntaxException ex) {
// Syntax error in the regular expression
}
至少,它似乎在Python中工作正常:
import re
text = """
este es un texto de prueba "para ver como se comporta " la funcion sobre esto
"para ver como se comporta " la funcion sobre esto "o sobre otro" lo q sea
"""
ret = ""
print text
reobj = re.compile(r'([^\" ])*(\".*?\")*', re.IGNORECASE)
for match in reobj.finditer(text):
if match.group() <> "":
ret = ret + match.group() + "|"
print ret
解析出引用的内容后,运行这对其余的,散装或一块一块的必要:
String text = "ABC DEF GHI JKL";
text = text.replaceAll("()+", " ");
// text: "ABC DEF GHI JKL"
杰夫,你在正确的轨道上,但也有一些错误在你的代码,即:(1)你忘了逃避否定字符类中的引号; (2)第一捕获组内的人体应该是非捕获变体; (3)如果第二组捕捉伙伴不参与比赛,则group(2)
返回空值,并且您没有为此进行测试; (4)如果在正则表达式中测试两个或多个空格而不是一个或多个,则不需要稍后检查匹配的长度。下面是修改后的代码:
import java.util.regex.*;
public class Test
{
public static void main(String[] args) throws Exception
{
String text = "blah blah \"boo boo boo\" blah blah";
Pattern p = Pattern.compile("(\"[^\"\\\\]*(?:\\\\.[^\"\\\\]*)*\")|( +)");
StringBuffer sb = new StringBuffer();
Matcher m = p.matcher(text);
while (m.find())
{
if (m.group(2) != null)
{
m.appendReplacement(sb, " ");
}
}
m.appendTail(sb);
System.out.println(sb.toString());
}
}
@Alan - 谢谢。我相应地更新了我的答案。 – 2008-11-05 06:34:49