简体   繁体   中英

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:

 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 :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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