[英]Extract text in Regular Expression in Javascript
In Javascript, I want to extract array from a string. 在Javascript中,我想从字符串中提取数组。 The string is
字符串是
var str = "abc (24 314 83 383)(-256)sa 0 (24 314) 1"
I want priority to be the text in parentheses then other text separated by white space. 我希望优先级是括号中的文本,然后是由空格分隔的其他文本。 So for the above example, the result should to be:
所以对于上面的例子,结果应该是:
result[0] = "abc"
result[1] = "24 314 83 383"
result[2] = "-256"
result[3] = "sa"
result[4] = "0"
result[5] = "24 314"
result[6] = "1"
I tried 我试过了
var pattern = /(.*?)[\s|\)]/g;
result = str.match(pattern);
but the result was: abc ,(24 ,314 ,83 ,383),(-256),sa ,0 ,(24 ,314),
但结果是:
abc ,(24 ,314 ,83 ,383),(-256),sa ,0 ,(24 ,314),
You can try this: 你可以试试这个:
let str = "abc (24 314 83 383)(-256)sa 0 (24 314) 1"; let replaced = str.replace(/(\\s*\\(|\\))/g, '<REP>'); let arrFromStr = replaced.split('<REP>').filter(w => w.length != 0);
Variable "replaced" replaces all 1) 0 or more spaces + "(", and 2) all ")" symbols to "" string. 变量“被替换”替换所有1)0或更多空格+“(”和2)所有“)”符号到“”字符串。 arrFromStr creates an array from string and split it with "".
arrFromStr从string创建一个数组并用“”分割它。 Then we check is the element of array empty, or not.
然后我们检查数组的元素是否为空。
Here's a solution using a regex object and exec
, which is safer than filtering out parenthesis with something like str.match(/\\w+|\\((.*?)\\)/g).map(e => e.replace(/^\\(|\\)$/g, ""))
: 这是一个使用正则表达式对象和
exec
的解决方案,它比使用str.match(/\\w+|\\((.*?)\\)/g).map(e => e.replace(/^\\(|\\)$/g, ""))
等过滤掉括号更安全str.match(/\\w+|\\((.*?)\\)/g).map(e => e.replace(/^\\(|\\)$/g, ""))
:
var str = "abc (24 314 83 383)(-256)sa 0 (24 314) 1"; var reg = /\\w+|\\((.*?)\\)/g; var match; var res = []; while (match = reg.exec(str)) { res.push(match[1] || match[0]); } console.log(res);
try this: 尝试这个:
var str = "abc (24 314 83 383)(-256)sa 0 (24 314) 1" var pattern = /\\((.*?)\\)|\\s?(\\S+)\\s?/g; var result = str.match(pattern).map(v => v.trim().replace(/^\\(|\\)$/g, '')); console.log(result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.