admin管理员组文章数量:1291030
How can I capture a word just after specific word in regex, I have to select everything between from - to and after to so there will be two capturing groups.
Example:
"From London to Saint Petersburg" I wanted to extract London
Saint Petersburg
from above string.
Im stuck with this code here, my current regex selecting to Saint Petersburg
i wanted to get rid word from
and to
from the selection.
/(?=to)(.*)/i
How can I capture a word just after specific word in regex, I have to select everything between from - to and after to so there will be two capturing groups.
Example:
"From London to Saint Petersburg" I wanted to extract London
Saint Petersburg
from above string.
Im stuck with this code here, my current regex selecting to Saint Petersburg
i wanted to get rid word from
and to
from the selection.
/(?=to)(.*)/i
Share
Improve this question
asked Sep 8, 2017 at 14:49
Wimal WeerawansaWimal Weerawansa
1572 gold badges16 silver badges35 bronze badges
3 Answers
Reset to default 7You can capture the two groups you need and then use match
to extract them:
s = "From London to Saint Petersburg"
console.log(
s.match(/From (.*?) to (.*)/).slice(1,3)
)
you can just use split()
and use /From | to /
, it will return an array containing split values
var str = "From London to Saint Petersburg";
var arr = str.split(/from | to /ig);
console.log(arr);
Here is sample code doing what you asks for:
<html>
<head>
</head>
<body>
</body>
<script>
var strIn = "From London to Saint Petersburg";
var regEx = /^From\s(.+?)\sto\s(.+?)$/;
var arrResult = regEx.exec(strIn);
var strOut = "Original:" + strIn + "<br>Result:<br>";
strOut += "1. " + arrResult[1] + "<br>";
strOut += "2. " + arrResult[2];
document.write(strOut);
</script>
</html>
Place this in a document. Open it with a browser. Here is how the result looks like:
Original:From London to Saint Petersburg Result: 1. London 2. Saint Petersburg
Hope it helps!
本文标签: javascriptRegex select word after specific wordStack Overflow
版权声明:本文标题:javascript - Regex select word after specific word - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741515512a2382861.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论