任何人都可以帮助我使用正则表达式替换所有单个字母与空格.例:
input: "this is a t f with u f array"
output: "this is with array".
Run Code Online (Sandbox Code Playgroud)
我的正则表达式是replaceAll("(\\s+[a-z]\\s+)"," ");
但它的工作原理如下:
input: "this is a t f with u f array"
output: "this is t f with f array".
Run Code Online (Sandbox Code Playgroud)
出现问题是因为replaceAll的工作方式.发生的事情是每次它替换它开始寻找它匹配的部分之后的部分,例如当你的模式运行时你得到结果
this is t with f array
Run Code Online (Sandbox Code Playgroud)
内部发生的事情是:
您需要使用的是一个名为"零宽度正向前瞻"的技巧如果您使用该模式:
(\\s+[a-z](?=\\s))
Run Code Online (Sandbox Code Playgroud)
第二个空间说"尝试匹配,但实际上并不认为它是比赛的一部分".因此,当下一场比赛发生时,它将能够将该空间用作其匹配的一部分.
您还需要使用空字符串替换,因为不会删除尾随空格,即
"this is a t f with u f array".replaceAll("(\\s+[a-z](?=\\s))","")
Run Code Online (Sandbox Code Playgroud)