Regexp with .exec not working - javascript

I want to match 3 letters and 3 digits with regexp and exec. But I dont get any result. Any idea what is wrong? The code is:
var regnr = "This is the pattern to match: WBJ124";
var patt = new RegExp("^\b[a-zA-Z]{3}\d{3}\b*$");
var sequence = '';
var grps = patt.exec(regnr);
if(grps!=null){
sequence = grps[0];
}
sequence is empty, but I expect it to be WBJ124
Best Regards

You have few mistakes in your regex like using ^ and $ when you are matching a substring in a longer string. Also you are using RegExp object that accepts a string literal hence requires double escaping.
You can use:
var regnr = "This is the pattern to match: WBJ124";
var patt = /\b[a-zA-Z]{3}\d{3}\b/; // or new RegExp("\\b[a-zA-Z]{3}\\d{3}\\b")
var grps = patt.exec(regnr);

Related

regex match everything between two different characters

I want to match a string between (but not including) these two characters: ? and &
Example string:
localhost/path/doc.html?970441179&token=specialtoken&actionurl=/portletaction/01654/0112
So from the above I want to match the string 970441179
var str = "?samplestring&";
var patt = /[?]([^&]*)[&]/g;
var res = patt.exec(str)[1];
'res' is your desired result.
Try this regex (\d+)(?=&):
var str = "localhost/path/doc.html?970441179&token=specialtoken&actionurl=/portletaction/01654/0112";
console.log(str.match(/(\d+)(?=&)/g));
Note that it will work just for that specific case.

Split string and get array using regExp in javascript/node js

I am writing js code to get array of elements after splitting using regular expression.
var data = "ABCXYZ88";
var regexp = "([A-Z]{3})([A-Z]{3}d{2})";
console.log(data.split(regexp));
It returns
[ 'ABCXYZ88' ]
But I am expecting something like
['ABC','XYZ','88']
Any thoughts?
I fixed your regex, then matched it against your string and extracted the relevant capturing groups:
var regex = /([A-Z]{3})([A-Z]{3})(\d{2})/g;
var str = 'ABCXYZ88';
let m = regex.exec(str);
if (m !== null) {
console.log(m.slice(1)); // prints ["ABC", "XYZ", "88"]
}
In your case, I don't think you can split using a regex as you were trying, as there don't seem to be any delimiting characters to match against. For this to work, you'd have to have a string like 'ABC|XYZ|88'; then you could do 'ABC|XYZ|88'.split(/\|/g). (Of course, you wouldn't use a regex for such a simple case.)
Your regexp is not a RegExp object but a string.
Your capturing groups are not correct.
String.prototype.split() is not the function you need. What split() does:
var myString = 'Hello World. How are you doing?';
var splits = myString.split(' ', 3);
console.log(splits); // ["Hello", "World.", "How"]
What you need:
var data = 'ABCXYZ88';
var regexp = /^([A-Z]{3})([A-Z]{3})(\d{2})$/;
var match = data.match(regexp);
console.log(match.slice(1)); // ["ABC", "XYZ", "88"]
Try this. I hope this is what you are looking for.
var reg = data.match(/^([A-Z]{3})([A-Z]{3})(\d{2})$/).slice(1);
https://jsfiddle.net/m5pgpkje/1/

Passing Parameter into function match

I am using the function match for a search engine, so whenever a user types a search-string I take that string and use the match function on an array containing country names, but it doesn't seem to work.
For example if I do :
var string = "algeria";
var res = string.match(/alge/g); //alge is what the user would have typed in the search bar
alert(res);
I get a string res = "alge": //thus verifying that alge exists in algeria
But if I do this, it returns null, why? and how can I make it work?
var regex = "/alge/g";
var string = "algeria";
var res = string.match(regex);
alert(res);
To make a regex from a string, you need to create a RegExp object:
var regex = new RegExp("alge", "g");
(Beware that unless your users will be typing actual regular expressions, you'll need to escape any characters that have special meaning within regular expressions - see Is there a RegExp.escape function in Javascript? for ways to do this.)
You don't need quotes around the regex:
var regex = /alge/g;
Remove the quotes around the regex.
var regex = /alge/g;
var string = "algeria";
var res = string.match(regex);
alert(res);
found the answer, the match function takes a regex object so have to do
var regex = new RegExp(string, "g");
var res = text.match(regex);
This works fine

Regex working fine in C# but not in Javascript

I have the following javascript code:
var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]"
var latexRegex = new RegExp("\\\[.*\\\]|\\\(.*\\\)");
var matches = latexRegex.exec(markdown);
alert(matches[0]);
matches has only matches[0] = "x=1 and y=2" and should be:
matches[0] = "\(x=1\)"
matches[1] = "\(y=2\)"
matches[2] = "\[z=3\]"
But this regex works fine in C#.
Any idea why this happens?
Thank You,
Miguel
Specify g flag to match multiple times.
Use String.match instead of RegExp.exec.
Using regular expression literal (/.../), you don't need to escape \.
* matches greedily. Use non-greedy version: *?
var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]"
var latexRegex = /\[.*?\]|\(.*?\)/g;
var matches = markdown.match(latexRegex);
matches // => ["(x=1)", "(y=2)", "[z=3]"]
Try non-greedy: \\\[.*?\\\]|\\\(.*?\\\). You need to also use a loop if using the .exec() method like so:
var res, matches = [], string = 'I have \(x=1\) and \(y=2\) and even \[z=3\]';
var exp = new RegExp('\\\[.*?\\\]|\\\(.*?\\\)', 'g');
while (res = exp.exec(string)) {
matches.push(res[0]);
}
console.log(matches);
Try using the match function instead of the exec function. exec only returns the first string it finds, match returns them all, if the global flag is set.
var markdown = "I have \(x=1\) and \(y=2\) and even \[z=3\]";
var latexRegex = new RegExp("\\\[.*\\\]|\\\(.*\\\)", "g");
var matches = markdown.match(latexRegex);
alert(matches[0]);
alert(matches[1]);
If you don't want to get \(x=1\) and \(y=2\) as a match, you will need to use non-greedy operators (*?) instead of greedy operators (*). Your RegExp will become:
var latexRegex = new RegExp("\\\[.*?\\\]|\\\(.*?\\\)");

Replace string that starts with specific character and ends with specific character in regular expression

I wanted to replace a string section that starts with a specific character and ends with specific character. At below, I demonstrate test case.
var reg = /pattern/gi;
var str = "asdfkadsf[xxxxx]bb";
var test = str.replace(reg,"") == "asdfkadsfbb"
console.log(test);
This pattern should work for replace anything between brackets (including the brackets):
var reg = /(\[.*?\])/gi;
var str = "asdfkadsf[xxxxx]bb";
var test = str.replace(reg,"") == "asdfkadsfbb"
based on your example, this works:
/\[.*]/gi

Categories

Resources