繁体   English   中英

javascript - 通过指定起始和结束字符来拆分字符串

[英]javascript - split string by specifying starting and ending characters

我有一个字符串(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'

使用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); 

在正则表达式中使用捕获括号时,捕获的文本也会在数组中返回。

请注意,这将有一个结尾""条目,因为您的字符串以@@结尾。 如果您不想这样,只需将其删除即可。


  • 如果您始终假设格式正确的字符串,则以下正则表达式产生相同的结果:

     /##|@@/ 

    * TJ Crowder评论

  • 如果您希望##@@之间有换行符,请将表达式更改为:

     /##([\\s\\S]*?)@@/ 
  • 如果你需要它表现更好,特别是使用更长的字符串更快地失败:

     /##([^@]*(?:@[^@]+)*)@@/ 

    * 基准

您可以##拆分,然后将每个结果拆分为@@ ,然后展平生成的数组,如下所示。

s.split('##').map(el => el.split('@@')).reduce((acc, curr) => acc.concat(curr))

请注意,如果原始字符串以@@结尾,则结果数组的最后一个元素将为空字符串,因此您可能需要将其删除,具体取决于您的用例。

您可以使用:

var s = '(100*##G. Mobile Dashboard||Android App ( Practo.com )||# of new installs@@-##G. Mobile Dashboard||Android App ( Practo.com )||# of uninstalls@@'

var arr = s.split(/(##.*?@@)/).filter(Boolean)

//=> ["(100*", "##G. Mobile Dashboard||Android App ( Practo.com )||# of new installs@@", "-", "##G. Mobile Dashboard||Android App ( Practo.com )||# of uninstalls@@"]
  • 使用捕获组在结果数组中获取拆分文本
  • filter(Boolean)来从数组中删除空结果

暂无
暂无

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

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