Sar*_*n S 5 javascript regex string
我有一个字符串 (100*##G. Mobile Dashboard||Android App ( Practo.com )||# of new installs@@-##G. Mobile Dashboard||Android App ( Practo.com )||# of uninstalls@@
我想以返回以下结果的方式拆分字符串(即它匹配以开头##和结尾的所有字符,并@@用匹配的字符拆分字符串)
["(100*", "G. Mobile Dashboard||Android App ( Practo.com )||# of new installs", '-', 'G. Mobile Dashboard||Android App ( Practo.com )||# of uninstalls'
Run Code Online (Sandbox Code Playgroud)
使用String.prototype.split()传递正则表达式。
var str = "(100*##G. Mobile Dashboard||Android App ( Practo.com )||# of new installs@@-##G. Mobile Dashboard||Android App ( Practo.com )||# of uninstalls@@";
var re = /##(.*?)@@/;
var result = str.split(re);
console.log(result);Run Code Online (Sandbox Code Playgroud)
当您在正则表达式中使用捕获括号时,捕获的文本也会在数组中返回。
请注意,这将有一个结束""条目,因为您的字符串以@@. 如果你不想要它,只需将其删除。
如果您总是假设一个格式良好的字符串,则以下正则表达式会产生相同的结果:
/##|@@/
Run Code Online (Sandbox Code Playgroud)
*评论由TJ Crowder
如果您希望在##和之间换行@@,请将表达式更改为:
/##([\s\S]*?)@@/
Run Code Online (Sandbox Code Playgroud)如果你需要它表现得更好,特别是用更长的字符串更快地失败:
/##([^@]*(?:@[^@]+)*)@@/
Run Code Online (Sandbox Code Playgroud)
*基准