Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
667 views
in Technique[技术] by (71.8m points)

regex - Javascript Regexp - Match Characters after a certain phrase

I was wondering how to use a regexp to match a phrase that comes after a certain match. Like:

var phrase = "yesthisismyphrase=thisiswhatIwantmatched";
var match = /phrase=.*/;

That will match from the phrase= to the end of the string, but is it possible to get everything after the phrase= without having to modify a string?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You use capture groups (denoted by parenthesis).

When you execute the regex via match or exec function, the return an array consisting of the substrings captured by capture groups. You can then access what got captured via that array. E.g.:

var phrase = "yesthisismyphrase=thisiswhatIwantmatched"; 
var myRegexp = /phrase=(.*)/;
var match = myRegexp.exec(phrase);
alert(match[1]);

or

var arr = phrase.match(/phrase=(.*)/);
if (arr != null) { // Did it match?
    alert(arr[1]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...