【问题标题】:JavaScript regexp replace spaces that match certain conditionJavaScript 正则表达式替换符合特定条件的空格
【发布时间】:2021-07-05 20:15:14
【问题描述】:

鉴于以下文字,我想将括号内的空格替换为“-”

str = 'these are the (1st 2nd and last) places'

// expected result
// 'these are the (1st-2nd-and-last) places'

换句话说,替换所有以'('和(something)开头,后跟(something)和')'的空格。

我开始了

/(?<=\(\w+)\s/g

但是(regex101 告诉我)“lookbehind 中的量词使其宽度不固定”(参考\w+)。有什么更好的方法来解决这个问题?

【问题讨论】:

    标签: javascript regex


    【解决方案1】:

    您使用了错误的正则表达式风格。在 JavaScript 中,您可以使用

    .replace(/(?<=\([^()]*)\s+(?=[^()]*\))/g, '-')
    

    请参阅regex demo。该模式匹配并替换为- 以下模式:

    • (?&lt;=\([^()]*) - 紧接在 ( 之前的位置以及除 () 之外的任何零个或多个字符
    • \s+ - 一个或多个空格
    • (?=[^()]*\)) - 除了() 之外,必须跟零个或多个字符,然后是) 字符。

    如果您使用的 JavaScript 环境较旧且不支持无限宽度后视,您可以使用

    .replace(/\([^()]+\)/g, function(x) { return x.replace(/\s+/g, '-') })
    

    也就是说,匹配圆括号之间的任何字符串,并在这些匹配项中将一个或多个空格的所有块替换为-

    console.log(
      'these are the (1st 2nd and last) places'.replace(/(?<=\([^()]*)\s+(?=[^()]*\))/g, '-')
    )

    console.log(
      'these are the (1st 2nd and last) places'.replace(/\([^()]+\)/g, function(x) { 
        return x.replace(/\s+/g, '-') 
      }))

    【讨论】:

    • 谢谢。你是对的,运行环境很重要。您的正则表达式演示在 Safari 14.1.1 中无法运行,但在 Visual Studio Code 中可以正常运行。也感谢有关“除 ( 和 ) 之外的零个或多个字符”的提示
    猜你喜欢
    • 2020-09-12
    • 1970-01-01
    • 2022-08-19
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 2013-03-09
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多