正则表达式:替换前面的空格:!?如果 它不存在,则



如果空间不存在,我想用 替换它:

input: "hello!", expect: "hello&nbsp!;"
input: "hello !", expect: "hello&nbsp!;"
input: "hello  !", expect: "hello&nbsp!;"
input: "hello !", expect: "hello&nbsp!"

最后一行实际上我得到了

input: "hello !", expect: "hello  !"

它增加了一个额外的 ,我想避免它

这是我到目前为止的代码:

text.replace(/ *([:!?])/g, " $1";

您可以通过在空格和标点符号之前匹配可选的 来实现这一点,并在替换中丢弃它们:

const strs = [
'hello!',
'hello !',
'hello  !',
'hello !',
'hello  !',
'hello    !'
];
console.log(strs.map(s => s.replace(/(?: )* *([:!?])/, ' $1')))

使用

.replace(/(?: |s)*([:!?])/, ' $1')

请参阅正则表达式证明。

解释

--------------------------------------------------------------------------------
(?:                      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代码

const strs = [
'hello!',
'hello !',
'hello  !',
'hello !',
'hello  !',
'hello    !'
];
console.log(strs.map(s => s.replace(/(?: |s)*([:!?])/, ' $1')))

最新更新