[英]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.