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);
Related
I've the pleasure to find all strings in our projects which are not angularjs expressions because we're going multi language (so every string which is not fully between curly braces).
What I wanna do is build a regex which matches all strings, which have no angular expressions (or part of the string is no angular expression).
The var names describe which should match (yes) and which shouldn't (nope).
var yes = "test";
var nope = "{{xyz}}";
var yes = "test {{xyz}}";
var nope = "{{::xyz}}";
var nope = "{{xyz}} {{abc}}"; //as whitespace is okay
Tried a lot of different stuff using negative lookaheads etc. but ended up with a not even close working regex.
"([^}}])+{{|"$
Maybe somebody can help me, as my head is like to explode...
Regex101: https://regex101.com/r/VePtVp/1
You may use following regex for match:
/"(?:\s*{{[^\s}]*}}\s*)+"/
RegEx Demo
RegEx Details:
": Match start quote
(?:: Start non-capture group
\s*{{[^\s}]*}}\s*: Match {{...}} string surrounded by optional whitespaces.
)+: End non-capture group. + matches 1 or more of this group
": Match end quote
Thanks to anubhava as his post and explanation helped me creating this regex here:
"(?!(\{\{[^\s]*\}\}\s*)+").*"
var yes = "test";
var nope = "{{xyz}}";
var yes = "test {{xyz}}";
var yes = "{test";
var yes = "{test} bearbeiten";
var yes = "{test}";
var nope = "{{::xyz}}";
var nope = "{{xyz}} {{abc}}";
var yes = "{{xyz}} test {{abc}}";
var yes = "{{xyz}} test {{abc}} temp {{var}}";
https://regex101.com/r/r9lmDL/2
Example string: #ABC ABC# #ABC# ABC
Example regex: /(?:[^#])(ABC)(?!#)/g (only matches ABC in the example)
I need to get a list of matches [[start,end],...] but not include the first group, which is only there because JS regex doesn't support lookbehind.
(Note: assume that the captured and uncaptured parts can be of any length, not just 1 or 3 characters like in the example)
Unfortunately, there is no way to get the indices where the groups matched inside the string.
As a workaround, make sure you capture the whole part of the pattern before the necessary capturing group/pattern part. Then, manipulate the match index and group legnth values as shown below:
var re = /([^#]|^)ABC(?!#)/g;
var str = 'ABC #ABC ABC# #ABC# ABC';
var pos = [];
while ((m = re.exec(str)) !== null) {
pos.push([m.index+m[1].length, m.index+m[0].length]);
}
console.log(pos);
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.
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
I'm trying to figure out a javascript regex that'll match an exact phrase that ends with a question mark, but isn't wrapped in quotes. So far I have this, which matches the phrase "some phrase", but I can't figure out how to match "some phrase?". Any help would be greatly appreciated.
(?<!"|')\some phrase\b(?!"|')
Lookbehinds don't exist in JavaScript. Use the following pattern:(?:[^"']|^)(some phrase\?)(?!["']). [^"']|^ means: any non-quote character or the beginning of a string.
Example:
var text = "....";
var pattern = /(?:[^"']|^)(some phrase\?)(?!["'])/;
var string = text.match(pattern);
var desiredString = string[1]; //Get the grouped text
var patternWithNQuoteGrouped = /([^"']|^)(some phrase\?)(?!["'])/;//Notice: No ?:
var replaceString = text.replace(patternWithNQuoteGrouped, '$1$2');
//$1 = non-quote character $2 = matched phrase
The parentheses around the phrase mark a referable group. (?: means: Create a group, but dereference it. To refer back to it, see the example code. Because lookbehinds don't exist in JavaScript, it's not possible to create a pattern which checks whether a prefix does not exist.
Try this:
var expr = /(^|(?!["']).)(some phrase\?)($|(?!["']).)/;
if (expr.test(searchText)) {
var matchingPhrase = RegExp.$2;
}
http://jsfiddle.net/gilly3/zCUsg/