我希望正则表达式用空格替换单个字符(或删除它们)。
例如,如果我有:
" I have played u with no i and no j o o o o x w x x s"
它应该返回:
" have played with no and"
我试过了:
\s+\w{1}\s+
但是当我使用它时,我得到:
" have played with no and no o o x x s"
我想念什么吗?我认为这与某种“重叠匹配”有关。
您的正则表达式是这样工作的:
先找到space
一个字符,然后再找到另一个字符,然后space
将其删除。在这种情况下,围绕一个字符的空格在测试另一个字符时无法匹配,例如
_a_b_c
^^^ -this part matches our pattern so it will be removed leaving
b_c and now neither `b` or `c` is surrounded with spaces so they will not
be removed
要解决此问题,只需在match中包含一个或多个空格(或字符串的开头),然后在其后加上一个字符like即可(^|\s+)\w
。
另外,要确保在此字符之后留出一个空格(或字符串的末尾),但不将该空格包含在匹配项中,则可以使用像这样的先行机制(?=\s+|$)
。
因此,如果使用Java,请尝试
String newString = yourString.replaceAll("(^|\\s+)\\w(?=\\s+|$)","");
和在JavaScript中
var replaced = text.replace(/(^|\s+)\w(?=\s+|$)/g,"")
BTW\w
可以匹配任何字符,[a-zA-Z0-9_]
因此您可以将其更改为[a-zA-Z]
只需要字母的字符。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句