Match multiple instances using RegExp and store values (JavaScript) - javascript

I would like to match all values with this pattern: #[\S]+. This will be used to get all names after an # in a comment. Example:
Here are some people: #Name1, #Name2, #Name3, #Name4
should return: ["Name1", "Name2", "Name3", "Name4"]
I have tried to use comment.match(/#[\S]+/ig) but this returns an array with the # symbol. I have tried to encapsulate the pattern with brackets: comment.match(/#([\S]+)/ig) but this doesn't help either. There may be more than 10 names that are matched so RegExp can't be used, and I'd rather not have to iterate through the array and strip it out.
Help appreciated :) .

As #KrzysztofWende you can use a look behind approach, or you can use capture groups:
With the regex:
/#(\w+)/ig
I replaced \S with \w, since otherwise the comma (,) is matched with Name1 as well.
Then the code reads:
var myString = "Here are some people: #Name1, #Name2, #Name3, #Name4";
var myRegexp = /#(\w+)/ig;
var match = myRegexp.exec(myString);
alert(match[1]);//do something useful with match[1]
Or in case you need to iterate over all possible matches:
var myString = "Here are some people: #Name1, #Name2, #Name3, #Name4";
var myRegexp = /#(\w+)/ig;
var match = myRegexp.exec(myString);
while (match != null) {
alert(match[1]);
match = myRegexp.exec(myString);
}
The solution makes use of capture groups: it numbers brackets starting from 1 (0 is the total match). In this case group 1 is thus (\w+).
JSFiddle demo.

Use positive look behind
/(?<=#)\S+/
/Edit
I've read that JavaScript doesn't support lookbehinds. So I recommend using:
result.map(function(a) {a.slice(1)})
On each

Related

Get string between “-”

I have this string: 2015-07-023. I want to get 07 from this string.
I used RegExp like this
var regExp = /\(([^)]+-)\)/;
var matches = regExp.exec(id);
console.log(matches);
But I get null as output.
Any idea is appreciated on how to properly configure the RegExp.
The best way to do it is to not use RegEx at all, you can use regular JavaScript string methods:
var id_parts = id.split('-');
alert(id_parts[1]);
JavaScript string methods is often better than RegEx because it is faster, and it is more straight-forward and readable. Any programmer can read this code and quickly know that is is splitting the string into parts from id, and then getting the item at index 1
If you want regex, you can use following regex. Otherwise, it's better to go with string methods as in the answer by #vihan1086.
var str = '2015-07-023';
var matches = str.match(/-(\d+)-/)[1];
document.write(matches);
Regex Explanation
-: matches - literal
(): Capturing group
\d+: Matches one or more digits
Regex Visualization
EDIT
You can also use substr as follow, if the length of the required substring is fixed.
var str = '2015-07-023';
var newStr = str.substr(str.indexOf('-') + 1, 2);
document.write(newStr);
You may try the below positive lookahead based regex.
var string = "2015-07-02";
alert(string.match(/[^-]+(?=-[^-]*$)/))

JavaScript: Replacing characters on both sides of a string

What I want to do is to match characters enclosed by ^^ and replace those ^^ while maintaining the string. In other words, turning this:
^^This is a test^^ this is ^^another test^^
into this:
<sc>This is a test</sc> this is <sc>another test</sc>
I got the regex to match them:
\^{2}[^^]+\^{2}
But I'm stuck there. I'm not sure what to do with the other .replace parameter:
.replace(/\^{2}[^^]+\^{2}/g, WHAT_TO_ADD_HERE?)
Any ideas?
You can use replace with regex and grouping like
var text = '^^This is a test^^ this is ^^another test^^'.replace(/\^\^(.*?)\^\^/g, '<sc>$1</sc>')
Here is a piece of code you can use:
var re = /(\^{2})([^^]+)(\^{2})/g;
var str = '^^This is a test^^ this is ^^another test^^\n\n<sc>This is a test</sc> this is <sc>another test</sc>';
var subst = '<sc>$2</sc>';
var result = str.replace(re, subst);
This is just an enhancement of your regex pattern where I added capturing groups. To improve performance and ensure you will be capturing all symbols between the ^^, you can use only one capturing group and . symbol with non-greedy quantificator:
var re = /\^{2}(.+?)\^{2}/g;
Have a look at the example.
In this case you need to use the group index to wrap the content.
var content = "^^This is a test^^ this is ^^another test^^";
content.replace(/\^{2}(.*?)\^{2}/g, '<sc>$1</sc>');
The (.*?) will help you to group the content and in your replace statement use $1 where 1 is the index of group.

non-capture group still showing in match

I know this topic has been thoroughly covered on StackOverflow, but I can't for the life of me get my regular expression to work. So without further repetitive ado ...
This is what I have.
String: <p model='cat'></p>
Regex: .match(/(?:model=')(.*)(?:')/g)
This is what my expression returns: model='cat'
This is what I want: cat
Why isn't my non capture group ignored? Is it that I don't understand what a non-capturing group does? Why isn't my Regex working?
The entire match will always be group 0, you need to access that specific group (group 1 in this case since the first group is non-capture), you can do it like this:
var str = "<p model='cat'></p>";
var regex = /(?:model=')(.*)(?:')/g
var match = regex.exec(str);
alert(match[1]); // cat
Fiddle
Also, I suppose you are probably wanting several matches within str, you could do that like this:
var str = "<p model='cat'></p><p model='dog'></p><p model='horse'></p>";
var regex = /(?:model=')([^']*)/g
var matches = [];
var match;
while (match = regex.exec(str)) {
matches.push(match[1]);
}
alert(matches); // cat,dog,horse
Fiddle
A non-capturing group is basically just a non-group ― a way to use parentheses without actually treating that part of the pattern as a group.
It looks like what you're actually looking for are the "match prefix but exclude" group (?<=) and the "match suffix but exclude" group (?=).
Note: This type of group does not seem to be supported in Internet Explorer.
If you use these, you get the desired result:
var str = "<p model='cat'></p><p model='dog'></p><p model='horse'></p>";
var regex = /(?<=model=')[^']*(?=')/g
var matches = str.match(regex);
console.log(matches);

extract all text inside braces into array of strings

I have a big string from which I would like to extract all parts that are inside round braces.
Say I have a string like
"this (one) that (one two) is (three )"
I need to write a function that would return an array
["one", "one two", "three "]
I tried to write a regex from some advice found here and failed, since I seem to only get the first element and not a proper array filled with all of them: http://jsfiddle.net/gfQzK/
var match = s.match(/\(([^)]+)\)/);
alert(match[1]);
Could someone point me in the right direction? My solution does not have to be regular expression.
You need a global regex. See if this helps:
var matches = [];
str.replace(/\(([^)]+)\)/g, function(_,m){ matches.push(m) });
console.log(matches); //= ["one", "one two", "three "]
match won't do as it doesn't capture groups in global regex. replace can be used to loop.
You are almost there. You just need to change a few things.
First, add the global attribute to your regex. Now your regex should look like:
/\(([^)]+)\)/g
Then, match.length will provide you with the number of matches. And to extract the matches, use indexes such as match[1] match[2] match[3] ...
You need to use the global flag, and multiline if you have new lines in there, and continually exec the result until you have all your results in an array:
var s='Russia ignored (demands) by the White House to intercept the N.S.A. leaker and return him to the United States, showing the two countries (still) have a (penchant) for that old rivalry from the Soviet era.';
var re = /\(([^)]+)\)/gm, arr = [], res = [];
while ((arr = re.exec(s)) !== null) {
res.push(arr[1]);
}
alert(res);
fiddle
For reference check out this mdn article on exec

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?
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]);
}
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).
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.
Let try this, I hope it work
var p = /\b([\w|\W]+)\1+(\=)([\w|\W]+)\1+\b/;
console.log(p.test('case1 or AA=AA ilkjoi'));
console.log(p.test('case2 or AA=AB'));
console.log(p.test('case3 or 12=14'));
If you want to get value after the regex excluding the test phrase, use this:
/(?:phrase=)(.*)/
the result will be
0: "phrase=thisiswhatIwantmatched" //full match
1: "thisiswhatIwantmatched" //matching group

Categories