Java正则表达式用两个空格替换单个字母和空格

时间:2011-03-09 19:01:52

标签: java regex

任何人都可以帮我用正则表达式替换所有带空格的单个字母。 示例:

 input: "this is a t f with u f array"
output: "this is       with     array".

我的正则表达式为replaceAll("(\\s+[a-z]\\s+)"," "); 但它的工作原理如下:

  input: "this is a t f with u f array"
 output: "this is   t f with   f array".

7 个答案:

答案 0 :(得分:6)

出现问题是因为replaceAll的工作方式。发生的事情是每次它替换它开始查看匹配的部分之后的部分,例如当你的模式运行时你得到结果

this is t with f array

内部发生的事情是:

  1. 匹配模式“这是一个与你的数组相关的”
  2. 匹配于“t”
  3. 替换为“”。
  4. 在最后一次匹配后开始匹配(“f with u f array”)
  5. 注意“f”不匹配,因为没有前导空格。
  6. 你需要使用的是一个名为“零宽度正向前瞻”的技巧如果使用模式:

    (\\s+[a-z](?=\\s))
    

    第二个空间说“尝试匹配,但实际上并不认为它是比赛的一部分”。因此,当下一场比赛发生时,它将能够将该空间用作其匹配的一部分。

    您还需要替换空字符串,因为不删除尾随空格,即

    "this is a t f with u f array".replaceAll("(\\s+[a-z](?=\\s))","")
    

答案 1 :(得分:2)

您可以尝试单词boundaries

"this is a t f with u f array".replaceAll("\\b[a-z]\\b"," ")

答案 2 :(得分:0)

嗯......也许是因为当“a”被发现并替换为“...... a t f ..”时,匹配器会查看下面的字符,即't'(空间已被消耗)。但话又说回来,我希望输出为“这与f数组有关。”

请尝试使用replaceAll("((\s+[a-z])*\s+)"," ")。但它有(不需要的?)副作用,任何长度的空白都将减少到一个空间。

答案 3 :(得分:0)

这个正在进行你的测试:

(\s+[a-z](\s[a-z])*\s+)

答案 4 :(得分:0)

replaceAll("\\b[a-z]\\b", " ");

将输出

this is       with     array

问题在于replaceAll如何处理事情。 \\s[a-z]\\s匹配

  

“a”

然后转到

  

“t f with u f array”

导致它错过第一个t

答案 5 :(得分:0)

你可以使用单词边界: -

    String s = "this is a t f with u f array";
    s = s.replaceAll("\\b\\w\\b\\s+", "");
    System.out.println(s); // this is with array

答案 6 :(得分:0)

字符串a =“这是一个带有u f数组的文件”;

a = a.replaceAll(“(\ s \ p {Alpha}(?= \ s))+((?= \ s)\ s)”,“”);

零宽度正向前瞻后跟捕获组中尾随空格的匹配产生了您正在寻找的内容:

这是数组