繁体   English   中英

在JavaScript中使用RegEx进行拆分

[英]Split using RegEx in JavaScript

假设我有一个广义字符串

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

我想使用分割字符串

"<constant_word>+<random_words_with_random_length>&"

我尝试过RegEx拆分

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

不幸的是,此RegEx拆分到最后一个'&',即

"<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"]

您可以用问号更改贪婪 ?

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

只需使用非贪婪匹配,只需放置一个? *+

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM