簡體   English   中英

如何使用JavaScript拆分此字符串?

[英]How do I split this string using JavaScript?

我有這個字符串

(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>) 

使用JavaScript,解析它的最快方法是什么

[b, 10, c, x, y]

我建議:

"(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>)".match(/[a-z0-9]+/g);
// ["b", "10", "c", "x", "y"]

JS小提琴演示

參考文獻:

嘗試這個:

'(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>)'.match(/[^(<+>)*-]+/g)

使用正則表達式

var pattern=/[a-zA-Z0-9]+/g
your_string.match(pattern).
var str = '(<<b>>+<<10>>)*<<c>>-(<<x>>+<<y>>) ';
var arr = str.match(/<<(.*?)>>/g);
// arr will be ['<<b>>', '<<10>>', '<<c>>', '<<x>>', '<<y>>']

arr = arr.map(function (x) { return x.substring(2, x.length - 2); });
// arr will be ['b', '10', 'c', 'x', 'y']

或者您也可以使用exec直接獲取捕獲組:

var regex = /<<(.*?)>>/g;
var match;
while ((match = regex.exec(str))) {
    console.log(match[1]);
}

這個正則表達式的好處是,您可以使用字符串中的任何內容,包括其他字母數字字符,而不會自動匹配它們。 只有<< >>中的標記才匹配。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM