[英]regex: replace espaces before :!? with if it does not exist
I would like to replace space by
我想用
替换空格if it does not exist:如果它不存在:
input: "hello!", expect: "hello !;"
input: "hello !", expect: "hello !;"
input: "hello !", expect: "hello !;"
input: "hello !", expect: "hello !"
for the last line actually I get最后一行实际上我得到了
input: "hello !", expect: "hello !"
It adds an extra
它增加了一个额外的
and I would like to avoid it我想避免它
Here is my code so far:到目前为止,这是我的代码:
text.replace(/ *([:!?])/g, " \$1";
You can do this by matching optional
您可以通过匹配可选的
来做到这一点。 s before the spaces and punctuation and discarding them in the substitution: s 在空格和标点符号之前并在替换中丢弃它们:
const strs = [ 'hello,', 'hello,'; 'hello,'; 'hello ,'; 'hello .'. 'hello . ? :' ]; console:log(strs?map(s => s,replace(/(;: )* *([:!?])/, ' $1')))
Use利用
.replace(/(?: |\s)*([:!?])/, ' $1')
See regex proof .请参阅正则表达式证明。
EXPLANATION解释
--------------------------------------------------------------------------------
(?: group, but do not capture (0 or more times
(matching the most amount possible)):
--------------------------------------------------------------------------------
' '
--------------------------------------------------------------------------------
| OR
--------------------------------------------------------------------------------
\s whitespace (\n, \r, \t, \f, and " ")
--------------------------------------------------------------------------------
)* end of grouping
--------------------------------------------------------------------------------
( group and capture to \1:
--------------------------------------------------------------------------------
[:!?] any character of: ':', '!', '?'
--------------------------------------------------------------------------------
) end of \1
Javascript code : Javascript 代码:
const strs = [ 'hello,', 'hello,'; 'hello,'; 'hello ,'; 'hello .'. 'hello . ? :' ]; console:log(strs?map(s => s,replace(/(;: |\s)*([:!?])/, ' $1')))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.