regex 有没有可能写一个正则表达式来查找不在成对的语音或引号内的多个空格?

f3temu5u  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(111)

我需要一个(TypeScript)正则表达式模式,它将匹配2个或更多不在语音或引号内的连续空格。
假设我有这个字符串:

"John    Smith" and Sarah Brown    are    having 'a     ' nice(" .    ")   day tod'   'ay.

我想匹配(然后删除)所有不在一对“”或“”内的2+白色空格子字符串。基本上,一对引号或引号中的任何内容都应该被忽略。有人能给我提供一个片段吗?
或者,有人能推荐一个合适的词法分析或解析npm库吗?我找到了this,但我不确定我是否能用它来执行此任务。

vlju58qv

vlju58qv1#

https://tsplay.dev/wX161N

const text = `"John    Smith" and Sarah Brown    are    having 'a     ' nice(" .    ")   day tod'   'ay.`

/*
from:
  /
    (               select as $1
      '[^']*'       text in ' quotes
      |             or
      "[^"]*"       text in " quotes
    )               end $1
    |
    ( )             select space as $2
    [ ]+            spaces 
  /g
to:
  $1                keep $1 text in quotes
  $2                keep $2 first space
*/

const result = text.replaceAll(/('[^']*'|"[^"]*")|( )[ ]+/g, '$1$2')
console.log(result)
// "John    Smith" and Sarah Brown are having 'a     ' nice(" .    ") day tod'   'ay.
// "John    Smith" and Sarah Brown ^^^are ^^^having 'a     ' nice(" .    ") ^^day tod'   'ay.

相关问题