Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 907
bryan sammon Avatar asked Dec 31 '10 17:12

bryan sammon


People also ask

How do you match a character sequence in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

How do you match anything up until this sequence of characters in regular expression?

If you add a * after it – /^[^abc]*/ – the regular expression will continue to add each subsequent character to the result, until it meets either an a , or b , or c . For example, with the source string "qwerty qwerty whatever abc hello" , the expression will match up to "qwerty qwerty wh" .

How do you match a character except one regex?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself. The character '. ' (period) is a metacharacter (it sometimes has a special meaning).


3 Answers

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]);
}
like image 75
DVK Avatar answered Oct 04 '22 21:10

DVK


phrase.match(/phrase=(.*)/)[1]

returns

"thisiswhatIwantmatched"

The brackets specify a so-called capture group. Contents of capture groups get put into the resulting array, starting from 1 (0 is the whole match).

like image 26
thejh Avatar answered Oct 04 '22 22:10

thejh


It is not so hard, Just assume your context is :

const context = "https://example.com/pa/GIx89GdmkABJEAAA+AAAA";

And we wanna have the pattern after pa/, so use this code:

const pattern = context.match(/pa\/(.*)/)[1];

The first item include pa/, but for the grouping second item is without pa/, you can use each what you want.

like image 42
AmerllicA Avatar answered Oct 04 '22 22:10

AmerllicA