【问题标题】:Regexp Get Text Between parenttheis [duplicate]正则表达式获取括号之间的文本[重复]
【发布时间】:2019-01-20 19:40:28
【问题描述】:

我有这样的字符串:

var str = "Hello (World) I'm Newbie";

如何使用正则表达式从上面的字符串中获取World?,对不起,我不了解正则表达式。

谢谢

【问题讨论】:

  • StackOverflow 不是免费的编码服务。所以希望你try to solve your own problem first。请更新您的问题以在minimal reproducible example 中显示您已经尝试过的内容。如需更多信息,请参阅How to Ask,并使用tour :) 你应该阅读正则表达式教程。
  • @Barmar,很抱歉我的问题,我被时间追了,所以我没有时间阅读正则表达式,我是正则表达式的初学者。

标签: javascript regex


【解决方案1】:

而不是使用正则表达式 - 使用 .split()...注意拆分中的转义字符。第一个拆分给出“World) I'm Newbie”,第二个拆分给出“World”。

var str = "Hello (World) I'm Newbie";

var strContent = str.split('\(')[1].split('\)')[0];
console.log(strContent); // gives "World"

【讨论】:

    【解决方案2】:

    假设至少有一个这样的词,您可以使用String#match 来完成。以下示例匹配括号之间的单词。

    console.log(
      "Hello (World) I'm Newbie"
      .match(/\(\w+\)/g)
      .map(match => match.slice(1, -1))
    )

    【讨论】:

      【解决方案3】:

      这可能对您的正则表达式有所帮助

      1. \w 匹配全世界
      2. + 加上另一个正则表达式
      3. [] 开始组
      4. ^ 除了
      5. (World) 匹配词

      var str = "Hello (World) I'm Newbie";
      var exactword=str.replace(/\w+[^(World)]/g,'')
      var filtered = str.replace(/(World)/g,'') 
      alert(exactword)
      alert(filtered)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-04-28
        • 2020-03-14
        • 1970-01-01
        • 2020-02-24
        • 2014-07-31
        • 1970-01-01
        相关资源
        最近更新 更多