JavaScript中使用正则表达式进行分割

5
假设我有一个通用字符串。
"...&<constant_word>+<random_words_with_random_length>&...&...&..."

我希望将字符串使用

分割。
"<constant_word>+<random_words_with_random_length>&"

我曾尝试使用正则表达式分割(RegEx split)

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

这个正则表达式可以分割到最后一个'&',但很遗憾。

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

如果我想要在获取第一个"&"时拆分,那么正则表达式代码会是什么?

例如要对字符串进行拆分的示例:

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

给我
["example&","string"]

尽管我想要的是...

["example&","this&is&a&sample&string"]
2个回答

5

您可以使用问号?来改变 贪婪度

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

如果我想要匹配到第二个'&',那么正则表达式的代码会有什么变化? - Varun Muralidharan
好的,那么它将是这样的:"example&ABC56748393&this&is&a&sample&string".split(/ABC.?&.?&/) - Varun Muralidharan
或者,可以少些重复:/ABC(?:.*?&){2}/(?:) 只是将其包装在一个非捕获组中,因此它可以被视为单个实体。 - Mattias Buelens

2

只需使用非贪婪匹配,将 *+ 后面加上一个 ?

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接