[英]Regex to match a single character in String
我希望正则表达式用空格替换单个字符(或删除它们)。
例如,如果我有:
" 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
要解决此问题,只需在匹配项中包含一个或多个空格(或字符串的开头),然后在其后添加一个字符,如(^|\\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]
字符。
我假设语言是javascript(请检查您的标签)。 我看到的问题是您的正则表达式包含空格,因此,如果您有“ aa bc”,则它与“ a”匹配,但是c本身之前或之后都没有空格。
var text=" a bb c dd e f g tt"
var re=/\s*\b\w\b/g //If you're coding in Java, remove the g: "\\s*\\b\\w\\b"
text.replace(re,"") //" bb dd tt"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.