【问题标题】:javascript - split string by specifying starting and ending charactersjavascript - 通过指定开始和结束字符分割字符串
【发布时间】:2016-08-07 10:23:39
【问题描述】:

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

【问题讨论】:

  • 初始字符串在这两个字符之间会有连字符。所以当用这个指定的字符分割字符串时,它需要在输出中给出连字符
  • 听起来很像您只想拆分##@@

标签: javascript regex string


【解决方案1】:

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

当您在正则表达式中使用Capturing parentheses 时,捕获的文本也会在数组中返回。

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


  • 如果你总是假设一个格式良好的字符串,下面的正则表达式会产生相同的结果:

    /##|@@/
    

    *评论者T.J. Crowder

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

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

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

    *Benchmark

【讨论】:

  • 看起来与/##|@@/ 得到的结果相同,这会更简单。 (假设一个格式良好的字符串。)
  • @T.J.Crowder 除非您有未封闭的结构,例如aaa##zzz。所以这取决于你对输入的期望。
  • 嘿,只是添加“...假设一个格式正确的字符串”。 :-)
  • 哈哈...我正在添加“...取决于您的期望...”:-)
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    你可以使用:

    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) 从数组中删除空结果

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-11-14
      • 2015-08-03
      • 2020-10-19
      • 2013-02-26
      • 2018-11-11
      • 2017-01-21
      • 2012-07-31
      相关资源
      最近更新 更多