javascript - 在 JavaScript 中使用 RegEx 进行拆分

标签 javascript regex string split

假设我有一个通用字符串

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

最佳答案

你可以用问号?改变贪心:

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

关于javascript - 在 JavaScript 中使用 RegEx 进行拆分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14386860/

相关文章:

JavaScript 不能使用 doctype html?

javascript - 为什么我在尝试使用 JavaScript substr() 函数时遇到此错误?

c# - 如何检查字符串是否包含字母或数字-正则表达式c#

regex - 根据外部或内部单引号以不同方式替换空格

c++ - 用长字符串中的另一个子字符串替换所有出现的子字符串

javascript - 无法使用新数据格式绘制图表

regex - Scala 正则表达式(由双引号分隔的字符串)

sql - 如何将数据库值连接成一个字符串?

python - 返回字符串的剥离空白的函数

javascript - 使用 Javascript 检测触摸屏设备