简体   繁体   English

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

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

I have this string 我有这个字符串

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

Using JavaScript, what is the fastest way to parse this into 使用JavaScript,解析它的最快方法是什么

[b, 10, c, x, y]

I'd suggest: 我建议:

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

JS Fiddle demo . JS小提琴演示

References: 参考文献:

尝试这个:

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

use regex 使用正则表达式

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']

Or you can also use exec to get the capture groups directly: 或者您也可以使用exec直接获取捕获组:

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

This regular expression has the benefit that you can use anything in the string, including other alphanumerical characters, without having them matched automatically. 这个正则表达式的好处是,您可以使用字符串中的任何内容,包括其他字母数字字符,而不会自动匹配它们。 Only those tokens in << >> are matched. 只有<< >>中的标记才匹配。

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

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