I am having some trouble with my regex in javascript.
I have the following code, that I think should match, but it doesn't.
var rgx = new RegExp("{\d+:(\d+)}");
if (rgx.test("{0:00000}") == true) {
alert("match");
}
else
{
alert("no match");
}
I am unsure if I should use test() here. I really want to catch the group, in my regex but exec() seems to give me the same result.
So what am I doing wrong?
The problem is that you need to escape the \ character in your regex:
var rgx = new RegExp("{\\d+:(\\d+)}");
Alternatively, you can use the literal syntax:
var rgx = /{\d+:(\d+)}/;
To capture the results, you should also use the .match function as opposed to test or exec. It will return null if it doesn't match and an array of at least one element if it does match.
There are multiple issues with the regex:
var rgx = new RegExp("{\d+:(\d+)}");
First (first noted by syazdani), you must string-escape the backslashes:
var rgx = new RegExp("{\\d+:(\\d+)}");
or better yet use a regex literal:
var rgx = /{\d+:(\d+)}/
Second, { and } have a special meaning in regex and should be escaped:
var rgx = /\{\d+:(\d+)\}/
Third, as noted by Ian, you might want to ensure the entire string is matched:
var rgx = /^\{\d+:(\d+)\}$/
RegExp#test returns a boolean true/false whether the string matches.
RegExp#exec returns an array holding the match and all captured groups if the string is matched, or null if the string is not matched:
var matches = /\{\d+:(\d+)\}/.exec("{0:000000}");
if(matches){
console.log(matches[1]); //logs "000000"
}
Related
So I have this (example) string: 1234VAR239582358X
And I want to get what's in between VAR and X. I can easily replace it using .replace(/VAR.*X/, "replacement");
But, how would I get the /VAR.*X/as a variable?
I think what you are looking for might be
string.match(/VAR(.*)X/)[1]
The brackets around the .* mark a group. Those groups are returned inside the Array that match creates :)
If you want to only replace what's in between "VAR" and "X" it would be
string.replace(/VAR(.*)X/, "VAR" + "replacement" + "X");
Or more generic:
string.replace(/(VAR).*(X)/, "$1replacement$2");
You can try use the RegExp class, new RegExp(`${VAR}.*X`)
You can store it as variable like this,
const pattern = "VAR.*X";
const reg = new RegExp(pattern);
Then use,
.replace(reg, "replacement");
If you
want to get what's in between VAR and X
then using .* would do the job for the given example string.
But note that is will match until the end of the string, and then backtrack to the first occurrence of X it can match, being the last occurrence of the X char in the string and possible match too much.
If you want to match only the digits, you can match 1+ digits in a capture group using VAR(\d+)X
const regex = /VAR(\d+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
Or you can match until the first occurrence of an X char using a negated character class VAR([^\r\nX]+)X
const regex = /VAR([^\r\nX]+)X/;
const str = "1234VAR239582358X";
const m = str.match(regex);
if (m) {
let myVariable = m[1];
console.log(myVariable);
}
What I'm doing...
I would like to have a string as such:
var match = "abcd|efhi|jklm|nopq|rstu|vwxyz";
And then check whether $(element).text() is one of the match.split("|") or simply within match.
I thought I'd be able to do if($('element').text().toLowerCase().match(/^(match)$/)) { however this wouldn't work.
Question
Why doesn't my match() work and what is my best way to resolve?
Your best way to resolve is to assign a regex to match
var match = /^(abcd|efhi|jklm|nopq|rstu|vwxyz)$/i;
Note that I added i for case insensitivity, so you can get rid of toLowerCase()
if($('element').text().match(match)) {
//...
}
My approach without using RegEx
var match = "abcd|efhi|jklm|nopq|rstu|vwxyz".split('|');
if (match.indexOf($('element').text().toLowerCase()) !== -1) {
// match found
}
To match a variable string, you can create a Regexp object:
var match = "^(abcd|efhi|jklm|nopq|rstu|vwxyz)$";
var reg = new RegExp(match, 'g');
if($('element').text().toLowerCase().match(reg)) {}
To make it case insensitive:
var match = "^(abcd|efhi|jklm|nopq|rstu|vwxyz)$";
var reg = new RegExp(match, 'ig');
if($('element').text().match(reg)){}
I'm having trouble trying to use multiple back references in a javascript match so far I've got: -
function newIlluminate() {
var string = "the time is a quarter to two";
var param = "time";
var re = new RegExp("(" + param + ")", "i");
var test = new RegExp("(time)(quarter)(the)", "i");
var matches = string.match(test);
$("#debug").text(matches[1]);
}
newIlluminate();
#Debug when matching the Regex 're' prints 'time' which is the value of param.
I've seen match examples where multiple back references are used by wrapping the match in parenthesis however my match for (time)(quarter)... is returning null.
Where am I going wrong? Any help would be greatly appreciated!
Your regex is literally looking for timequarterthe and splitting the match (if it finds one) into the three backreferences.
I think you mean this:
var test = /time|quarter|the/ig;
Your regex test simply doesn't match the string (as it does not contain the substring timequarterthe). I guess you want alternation:
var test = /time|quarter|the/ig; // does not even need a capturing group
var matches = string.match(test);
$("#debug").text(matches!=null ? matches.join(", ") : "did not match");
function listPlayers(subject){
var players=[];
var myregexp = /(\S*)(?:,\s|$)/g;
var match = myregexp.exec(subject);
while (match != null) {
players.push(match[1]);
match = myregexp.exec(subject);
}
return players;
}
The string I'm trying to match is like this �r Henderson�r�f, Pedrin�r�f, �c~�lArthur�r�f, John�r�f
The output I expect is an array like this ['Henderson�r�f', 'Pedrin�r�f', '�c~�lArthur�r�f', 'John�r�f']
What I don't understand is on regex buddy everything seems ok.
Try changing the regexp to:
var myregexp = /(\S+)(?:,\s|$)/g;
I think the loop may be because it repeatedly matches an empty string at the end.
Since I don't think you're interested in getting zero-length names, this is probably a better regexp in general.
Just for interest, a perhaps simpler way using a zero-width positive lookahead assertion:
function listPlayers( subject ) {
return subject.match( /\S+(?=,\s|$)/g );
}
I have the following string: pass[1][2011-08-21][total_passes]
How would I extract the items between the square brackets into an array? I tried
match(/\[(.*?)\]/);
var s = 'pass[1][2011-08-21][total_passes]';
var result = s.match(/\[(.*?)\]/);
console.log(result);
but this only returns [1].
Not sure how to do this.. Thanks in advance.
You are almost there, you just need a global match (note the /g flag):
match(/\[(.*?)\]/g);
Example: http://jsfiddle.net/kobi/Rbdj4/
If you want something that only captures the group (from MDN):
var s = "pass[1][2011-08-21][total_passes]";
var matches = [];
var pattern = /\[(.*?)\]/g;
var match;
while ((match = pattern.exec(s)) != null)
{
matches.push(match[1]);
}
Example: http://jsfiddle.net/kobi/6a7XN/
Another option (which I usually prefer), is abusing the replace callback:
var matches = [];
s.replace(/\[(.*?)\]/g, function(g0,g1){matches.push(g1);})
Example: http://jsfiddle.net/kobi/6CEzP/
var s = 'pass[1][2011-08-21][total_passes]';
r = s.match(/\[([^\]]*)\]/g);
r ; //# => [ '[1]', '[2011-08-21]', '[total_passes]' ]
example proving the edge case of unbalanced [];
var s = 'pass[1]]][2011-08-21][total_passes]';
r = s.match(/\[([^\]]*)\]/g);
r; //# => [ '[1]', '[2011-08-21]', '[total_passes]' ]
add the global flag to your regex , and iterate the array returned .
match(/\[(.*?)\]/g)
I'm not sure if you can get this directly into an array. But the following code should work to find all occurences and then process them:
var string = "pass[1][2011-08-21][total_passes]";
var regex = /\[([^\]]*)\]/g;
while (match = regex.exec(string)) {
alert(match[1]);
}
Please note: i really think you need the character class [^\]] here. Otherwise in my test the expression would match the hole string because ] is also matches by .*.
'pass[1][2011-08-21][total_passes]'.match(/\[.+?\]/g); // ["[1]","[2011-08-21]","[total_passes]"]
Explanation
\[ # match the opening [
Note: \ before [ tells that do NOT consider as a grouping symbol.
.+? # Accept one or more character but NOT greedy
\] # match the closing ] and again do NOT consider as a grouping symbol
/g # do NOT stop after the first match. Do it for the whole input string.
You can play with other combinations of the regular expression
https://regex101.com/r/IYDkNi/1
[C#]
string str1 = " pass[1][2011-08-21][total_passes]";
string matching = #"\[(.*?)\]";
Regex reg = new Regex(matching);
MatchCollection matches = reg.Matches(str1);
you can use foreach for matched strings.