我想要一个正则表达式用空格替换单个字符(或删除它们)。
例如,如果我有:
" 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"
我错过了什么吗?我认为这与某种“重叠匹配”有关。
最佳答案
你的正则表达式是这样工作的:
找到空格
,然后找到一个字符,然后找到另一个空格
,然后将其删除。在这种情况下,在测试另一个字符时,一个字符周围的空格无法匹配,就像
_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
要解决此问题,只需在匹配中包含一个或多个空格(或字符串开头)以及其后的一个字符,如 (^|\s+)\w
。
另外,为了确保此字符之后至少有一个空格(或字符串末尾),但要在匹配中不包含此空格,您可以使用 look-ahead类似于 (?=\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]
如果您只想要字母。
关于java - 正则表达式匹配字符串中的单个字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21878526/