Javascript Regex-如何基于正则表达式将字符串拆分为数组

Javascript Regex - How to split string to an array based on regex

本文关键字:字符串 拆分 数组 正则表达式 Regex- 何基于 Javascript      更新时间:2023-09-26

我有一个字符串:

"<b>Dispatcher Number1 $CREATED_NEW_INCIDENT$ </b> $BASED_ON$ 1 $EVENTS$"

我想创建一个数组,它只包括以$开头和结尾的单词。对于这个例子,我正在寻找的结果是:

["$CREATED_NEW_INCIDENT$","$BASED_ON$", "$EVENTS$"]

我知道我可以用regex做这件事,但我还没有成功。此外,当我找到正确的正则表达式时,我该怎么办?分开?

您不需要拆分它们。只需使用正则表达式进行匹配

/'$[^$]+'$/g

像这个

var str = "<b>Dispatcher Number1 $CREATED_NEW_INCIDENT$ </b> $BASED_ON$ 1 $EVENTS$";
var arr = str.match(/'$[^$]+'$/g);

只需使用$开始匹配,直到找到$

var regEx = /'$.*?'$/g;
console.log(data.match(regEx));
# [ '$CREATED_NEW_INCIDENT$', '$BASED_ON$', '$EVENTS$' ]

此处

  • .表示匹配任意字符。

  • .*表示匹配任何字符,用于零次或多次

  • .*?表示匹配任何字符,零次或多次,但只匹配尽可能少的字符。

如果我们在.*?中不使用?,它将从第一个$符号匹配到最后一个$符号。

您可以使用:

var s = "<b>Dispatcher Number1 $CREATED_NEW_INCIDENT$ </b> $BASED_ON$ 1 $EVENTS$";
var m = s.match(/('$[^$]*'$)/g);
//=> ["$CREATED_NEW_INCIDENT$", "$BASED_ON$", "$EVENTS$"]

您也可以使用:

"<b>Dispatcher Number1 $CREATED_NEW_INCIDENT$ </b> $BASED_ON$ 1 $EVENTS$".match(/'$['w]+'$/g)