Regex trouble in JavaScript - javascript

I am trying to extract data from a string using RegEx , but i am getting a NULL value as result.
here is my current code
var re = /(\[cid=(?:[0-9]*)(?:(?:,\[[^]]*\][^]]*)?|(?:,[^]]*))\])/;
var str = '[cid=5555,[CONSTIMG]5555.jpg]The Sample text is awesome';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
}
console.log(m[0]);
The value that i am getting back is NULL.
If anyone can point me in the right direction, that would be very helpful.
Thanks in advance.

Your expression matches PCRE regular expression syntax but not JavaScript because JavaScript requires that square brackets inside a character class be escaped with \. This is what you want:
(\[cid=(?:\d*)(?:(?:,\[[^\]]*\][^\]]*)?|(?:,[^\]]*))\])
Explained: https://regex101.com/r/pN4vP4/2

Related

Javascript regular expression : match 2 substrings in any order

After reading how to write a regexp in Javascript, I'm still pretty confused how to write this one...
I want to match every string containing at least one occurence of 2 substrings, in any order.
Say sub1 = "foo" and sub2 = "bar"
foo => doesn't match
bar => doesn't match
foobar => matches
barfoo => matches
foohellobar => matches
Could somebody help me with this ?
Additionnally, I'd like to exclude another substring. So it would match the strings containing the 2 substrings like before, but not containing a sub3, regardless of its order with the 2 others.
Thanks a lot
You can use indexOf:
str.indexOf(sub1) > -1 && str.indexOf(sub2) > -1
Or includes in ES6:
str.includes(sub1) && str.includes(sub2)
Or if you have an array of substrings:
[sub1, sub2/*, ...*/].every(sub => str.includes(sub));
This will work:
/.*foo.*bar|.*bar.*foo/g
.* matches 0 or many characters (where . matches any character and * stands for 0 or many)
| is regex' or operator
Generated code from regex101:
var re = /.*foo.*bar|.*bar.*foo/g;
var str = 'foobar';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
DEMO
That being said, better use Oriol's answer using indexOf() or includes().
I would not use a complicated regex, but instead just used logical operand &&.
var param = 'foobar';
alert(param.match(/foo/) && param.match(/bar/) && !param.match(/zoo/));
param = 'foobarzoo';
alert(param.match(/foo/) && param.match(/bar/) && !param.match(/zoo/));

Regex match letters not inside single quote

I need to match all charecters and digits(\w) inside the string which not inside the single quote (\')
For instance I have string:
param : 'test' .param4 'zzzz' param8 * 'rrrr'
from that string I need to get:
- param
- param4
- param8
Thx for any advance.
You can use this lookahead based regex:
/(?=(?:(?:[^']*'){2})*[^']*$)\b\w+\b/gm
RegEx Demo
This regex will match a word if that word is outside single quotes by using a lookahead to make sure there are even number of quotes after each word. This assumes unescaped quotes are balanced.
Code:
var re = /(?=(?:(?:[^']*'){2})*[^']*$)\b\w+\b/gm;
var str = 'param : \'test\' .param4 \'zzzz\' param8 * \'rrrr\' class2.class3*dsaasd';
var m;
var result;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex)
re.lastIndex++;
res.push(m[0]);
}
console.log(result);

How to use a Regular Expression in JavaScript which contains special characters

Sorry, probably being dumb this morning, but I don't know much about regular expressions, but have created something I want to use with https://regex101.com/
But... I can't use the code they suggest in Javascript without escaping it first.
Here's the regex: (?<=color:\s)([a-z]+)
Which, does what I want (matching a word after color: in a CSS file)
But, the code they suggest to use in JS is:
var re = /(?<=color:\s)([a-z]+)/g;
var str = ' color: black';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
The first line, won't work, so I escaped it to: var re = /\(?<=color:\s\)([a-z]+)/i which stops the Javascript error, but won't match the strings any more.
What am I doing wrong?
As an aside... can anyone point me to expanding this regex to exclude anything followed by a bracket? I am trying to get color names only, so "color: black;" should match, also "box-shadow: black... etc" should match, but ideally, not "color: rgb(... etc"
It is true that JS does not support look-behinds, although there are workarounds:
Reverse the string and then matches that enables using look-aheads
Use capturing groups
Use a while loop with re.lastIndex manipulation
In this case, it is much easier to use the capturing group:
var re = /\bcolor:\s*([a-z]+)/ig;
var str = ' color: black';
var m;
while ((m = re.exec(str)) !== null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// m[1] is holding our value!
document.getElementById("res").innerHTML = m[1];
}
<div id="res"/>

javascript regex pattern for _water_glass

I need a javascript regex pattern to test a schema variable, so that it should have either of the following.
It can start with any character followed by "_water_glass" and must not be anything after water_glass like "xxxx_water_glass"
or
It can be just "water_glass" not necessary to have character before water_glass and must not be anything after water_glass.
Could anyone help on this please to get the regex pattern.
Try this simply /^.*_?\_water_glass/
var re = /^.*_?_water_glass/mg;
var str = 'horse.mp3_country_code\n4343434_country_code\n_country_code';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
DEMO https://regex101.com/r/gB9zL7/2
Here you are:
^(?:.+_|)water_glass$
Details:
^- start of string
(?:.+_|) - an optional 1+ chars other than line break chars, as many as possible, up to the last _ including it
water_glass - a water_glass substring
$ - end of string.
See this regex demo and a demo code below:
var re = /^(?:.+_|)water_glass$/gm;
var str = 'xxxx_water_glass\nwater_glass';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}

selecting with regex content between two points

I always have a hard time with regex..
I'm trying to select the text between (taking into acount the before and after)
'window.API=' and ';' //for window.API= '--API--';
and other cases like:
'window.img_cdn=' and ';' //for window.img_cdn= '--imgCDN--';
any tips on witch regex concepts I should use would be a great help!
If you want to capture the content between 'xx' you can use a regex like this:
'(.*?)'
working demo
For the sample text:
window.API= '--API--';
window.img_cdn= '--imgCDN--';
You will capture:
MATCH 1
1. [13-20] `--API--`
MATCH 2
1. [40-50] `--imgCDN--`
The javascript code you can use is:
var re = /'(.*?)'/g;
var str = 'window.API= \'--API--\';\nwindow.img_cdn= \'--imgCDN--\';';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// View your result using the m-variable.
// eg m[0] etc.
}
On the other hand, if you specifically want to capture the content for only those entries, then you can use this regex:
window\.(?:API|img_cdn).*?'(.*?)'
If you want to match any text between a <some string>= sign and a semicolon, here you go:
(?:[\w\.]+\s*=\s')(.+)(?:';)$
This regex pattern will match a full string if an escaped apostrophe is present in the string: //for window.img_cdn = '--imgCDN and \'semicolon\'--';
JavaScript code:
var re = /(?:[\w\.]+\s*=\s')(.+)(?:';)$/gm;
var str = '//for window.img_cdn= \'--imgCDN--\';\n//for window.img_cdn = \'--imgCDN and semicolon = ;;;--\';';
var m;
while ((m = re.exec(str)) != null) {
if (m.index === re.lastIndex) {
re.lastIndex++;
}
// view results
}
The required text is in the 1st captured group. In case there is a semicolon in the text you are looking for, you will correctly match it due to the $ anchor.
See demo here

Categories