![](/img/trans.png)
[英]Need to extract values from string in Javascript between words and characters
[英]Extract text between two words from entire string JavaScript
我有一个字符串,我想在其中提取两个文本之间的所有单词,例如:
var str="This is the number I want +2143334 !, again this is the next number I want +234343443 !, last number I want +76645 !, fininshed";
var ext = str.split('want').pop().split('!,').shift();
alert(ext);
但这只给出+2143334
。 我想要的是所有三个匹配项,即:
+2143334, +234343443, +76645
如何做呢?
您可以使用下面的正则表达式来捕捉+
接着用后1+位数want
:
/want\s*(\+\d+)/g
参见regex演示 。
在这里, want
匹配一个文字子字符串,然后\\s*
匹配0+个空格字符,而(\\+\\d+)
捕获到组1中的一个加号和一个1+位数。
在Chrome中,您甚至可以使用str.match(/(?<=want\\s*)\\+\\d+/g)
,但并非所有浏览器都已支持ECMAScript 2018酷正则表达式功能。
JS演示:
var str="This is the number I want +2143334 !, again this is the next number I want +234343443 !, last number I want +76645 !, fininshed"; var m,results = []; var rx = /want\\s*(\\+\\d+)/g; while(m=rx.exec(str)) { results.push(m[1]); } console.log(results);
您可以使用RegExp (?<=want )([^ ]*)(?= !)
:
(?<=want )
确保want[space]
位于表达式后面
([^ ]*)
匹配除空格以外的任何内容
(?= !)
确保[space]!
在你的表情之后
添加g
以使RegEx 全局化 。
var str = "This is the number I want +2143334 !, again this is the next number I want +234343443 !, last number I want +76645 !, fininshed"; console.log(str.match(/(?<=want )([^ ]*)(?= !)/g));
实际上,您的代码给出的结果是+76645。 无论如何,更简单的方法如下:
var str="This is the number I want +2143334 !, again this is the next number I want +234343443 !, last number I want +76645 !, fininshed"; // To extract numbers only var vetStrings = str.match(/\\d+/g); console.log(vetStrings); // To cast the result as numbers var vetNumbers = vetStrings.map(Number); console.log(vetNumbers);
:)
我的建议:
var reg = /(?<=want\s)[a-zA-Z0-9+]+(?=\s\!)/g;
var yourText = 'This is the number I want +2143334 !, again this is the next number I want +234343443 !, last number I want +76645 !, fininshed';
var resultArray = yourText.match(reg);
console.log(resultArray);
哪里
想要
(\\ s为空格)是您的匹配项之前的文本,并且
\\ s \\!
如果是比赛后的文字。
最好的祝福 ;)
你可以用这个
str.match(/want\s[a-zA-Z0-9+!@#$%^&*()_+={}|\\]+\s!/g).map((e)=>e.split(' ')[1])
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.