【问题标题】:Split using RegEx in JavaScript在 JavaScript 中使用 RegEx 进行拆分
【发布时间】:2013-01-17 19:44:46
【问题描述】:

假设我有一个通用字符串

"...&<constant_word>+<random_words_with_random_length>&...&...&..."

我想用

分割字符串
"<constant_word>+<random_words_with_random_length>&"

为此我尝试过 RegEx 拆分

<string>.split(/<constant_word>.*&/)

不幸的是,这个正则表达式拆分到最后一个“&”,即

"<constant_word>+<random_words_with_random_length>&...&...&"

如果我希望它在获得第一个“&”时进行拆分,那么 RegEx 代码会是什么?

字符串拆分示例

"example&ABC56748393&this&is&a&sample&string".split(/ABC.*&/)

给我

["example&","string"]

而我想要的是..

["example&","this&is&a&sample&string"]

【问题讨论】:

    标签: javascript regex string split


    【解决方案1】:

    你可以用问号?改变贪婪

    "example&ABC56748393&this&is&a&sample&string".split(/&ABC.*?&/);
    // ["example", "this&is&a&sample&string"]
    

    【讨论】:

    • 如果我想要直到第二个'&',那么正则表达式代码会发生什么变化?
    • 好的,那就是这个 "example&ABC56748393&this&is&a&sample&string".split(/ABC.*?&.*?&/)
    • 或者,重复较少:/ABC(?:.*?&amp;){2}/(?:) 只是将其包装在一个非捕获组中,因此可以将其视为单个实体。
    【解决方案2】:

    只需使用非贪婪匹配,在*+ 之后放置?

    <string>.split(/<constant_word>.*?&/)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-19
      • 1970-01-01
      • 2022-01-03
      • 2015-05-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多