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
Add a ment  | 

3 Answers 3

Reset to default 7

You 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