简体   繁体   English

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

[英]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&nbsp!;"
input: "hello !", expect: "hello&nbsp!;"
input: "hello  !", expect: "hello&nbsp!;"
input: "hello !", expect: "hello&nbsp!"

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&nbsp.&nbsp? :' ]; 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&nbsp.&nbsp? :' ]; console:log(strs?map(s => s,replace(/(;: |\s)*([:!?])/, ' $1')))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM