Regex for matching substring in JavaScript using VCS - javascript

I'm currently working on a short program in JavaScript that matches substrings within string, with a wildcard character in between.
let string1 = "The man is outside.";
let string2 = "I have two minutes.";
let string3 = "The men are here.";
I'm trying to find a regex expression that will encompass "m_n".
I've been trying to use the following function:
let matching = function(string) {
if (string.match(^m.*n$)) {
console.log("it does");
}
else {
console.log("it doesnt");
}
}
But I keep getting the error "SyntaxError: Unexpected token ^".
Does anyone have any pointers?

The problem is you forgot to assign / (forward slash).
And I recommend use test instead of match in if statement.
let string = "msdfsxn";
if (/^m.*n$/.test(string)) {
console.log("it does");
} else {
console.log("it doesn't");
}

I'm guessing that maybe,
m[^n]n
or
\bm[^n]n\b
or
\bm.*?n\b
might be close, or maybe not.
Demo 1
Demo 2
If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.
const regex = /m[^n]n/gm;
const str = `The man is outside.
I have two minutes.
The men are here.`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}

Related

Regex NodeJS Javascript not applying

I have the following node.js code:
let regex = /^<#&\!?(\d+)>$/g;
console.log("Before match ", gettingargR) // gettingargR = <#&702877893436375100> or <#&!702877893436375100>
gettingargR = gettingargR.match(regex);
console.log("After match ", gettingargR)
console.log("After match value", gettingargR[0])
My target (expected) return is After match [ '702877893436375100' ] and After match value 702877893436375100
When I try to achieve this, console returns:
Before match <#&702877893436375100>
After match [ '<#&702877893436375100>' ]
After match value <#&702877893436375100>
Which means my regex isn't applying. How can I apply it to my string?
You need to remove the g flag from your regexp. The global flag turns off the capture group because it needs to return multiple values therefore the interpretation of the return array changes from a specification of the match to a list of complete matches.
let regex = /^<#&\!?(\d+)>$/; // remove the g flag
console.log("Before match ", gettingargR);
gettingargR = gettingargR.match(regex);
console.log("After match ", gettingargR)
console.log("After match value", gettingargR[1]); // capture group is element 1
Without the g flag the interpretation of the result is different. The return array now has the following structure:
[
'<#&702877893436375100>', // full match
'702877893436375100', // first capture group
// second capture group (if any),
// third capture group (if any),
// etc..
]
For matching all in the big file you can use exec function. For simple first match use reg without "g" flag:
Sample:
const matchAll = (str, reg) => {
let m;
let result = [];
do {
m = reg.exec(str);
if (m) {
result.push(m[1]);
}
} while (m);
return result;
};
gettingargR = `<#&702877893436375100>
<#&!702877893436375100>`;
let regex = /^<#&\!?(\d+)>$/gm;
console.log("After match ", matchAll(gettingargR, regex));
Maybe this could help.
const regex = /^<#&\!?(\d+)>$/g;
const str = `<#&702877893436375100>`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Verified from https://regex101.com/

Regex to find the best matching subsetof a word

I have a list of coma separated words like cooler,bestwishes,congrat. I want to use regex to find the best matching word in this list. e.g Congratulations or Congrats matches congrat in the above list.
I have tried the regex below but it only works if the word in regex is the subset.
const regex = /[^,]*congratulation[^,]*/g;
const str = `this,cart,open,best-wishes,congrat`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
Is this possible using regex ?
Instead of searching for the target word's substring in a list of words you can search list of words in target word. That will reduce complexity and make it easier.
let words = ["cool","bestwishes","congrat","greatjob","welldone","kudos","thumbsup","keeprocking","rock","congrats"];
let word = "keeprockingbuddy";
let match = getMatchingWords(words,word);
console.log(match); // ["keeprocking", "rock"]
match = getMatchingWords(words,"Congratulations");
console.log(match); // ["congrat"]
function getMatchingWords(words,target){
let ans = [];
words.forEach((w)=>{
let found = target.match(new RegExp(w,"i"));
if(found){
ans.push(w);
}
})
ans = ans.length ? ans:"not found";
return ans;
}
Hope it answers your question.

RegEx mismatch in node.js [duplicate]

This question already has answers here:
Why do regex constructors need to be double escaped?
(5 answers)
Closed 3 years ago.
Consider the following regex:
^[^-\s][a-zA-Z\sàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ\d!##$\+%&\'*]{1,20}$
I did try it on https://regexr.com/ using as test Collection '98 and matches.
I then did implement it in Node.js:
const myRegex = '^[^-\s][a-zA-Z\sàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ\d!##$\+%&\'*]{1,20}$';
const name = 'Collection \'98';
if (!name.match(myRegex))
console.log('NOK');
else
console.log('OK');
However, it always prints NOK.
Why doesn't the validation work via app?
I'm not sure about your codes, however it seems to me that your expression is correct and it works.
This snippets shows that it would return a match.
const regex = /[^-\s][a-zA-Z\sàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ\d!##$\+%&\'*]{1,20}/gm;
const str = `Collection '98`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
You can test/modify your expressions in this link.
It appears that you might have forgotten to add your expression in between two forward slashes, which you can simply fix it using /expression/.
Enclose your regex between slashes (/) instead of quotation marks " and it'll work:
const myRegex = /^[^-\s][a-zA-Z\sàèìòùÀÈÌÒÙáéíóúýÁÉÍÓÚÝâêîôûÂÊÎÔÛãñõÃÑÕäëïöüÿÄËÏÖÜŸçÇßØøÅåÆæœ\d!##$\+%&\'*]{1,20}$/;
const name = 'Collection \'98';
if (!name.match(myRegex))
console.log('NOK');
else
console.log('OK');

how to match '\u' codes for all the emojis with regexp?

I want to find match all the strings which will have emojis in the form of \u codes. I'm trying with below regexp but is not working.
/([\uE000-\uF8FF]|\uD83C[\uDC00-\uDFFF]|\uD83D[\uDC00-\uDFFF]|[\u2694-\u2697]|\uD83E[\uDD10-\uDD5D])/g
But, it is not detecting. I want to match and get
\ud83d\ude04\ud83d\ude04\ud83d\ude04\ud83d\ude04\ud83d\ude04\ud83d\ude04
these type of characters.
Well if you want to match emojis in the format \uXXXX using Regex, you can use this Regex:
/\\u[a-z0-9]{4}/gi
This is a simple Demo:
const regex = /\\u[a-z0-9]{4}/gi;
const str = `This is a pragraph \\ud83d having some emojis like these ones:
\\ude04
\\ud83d
\\ude04
Have you seen them?
\\ud83d\\ude04
Great!
`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
The regex you wrote won't work because you were not escaping the \.

Best way to get the word right before a certain word in javascript

I have the following string
this is the string and THIS is the word I want
I've tried using a regex for this:
var to_search = "is"
var regex = "/\S+(?="+to_search+")/g";
var matches = string.match(regex);
And I wanted matches to contain "THIS" (word that comes after the second if) but it does not seem to be working
Any idea? Thanks
regex101.com is a really great site to test your regex and it even generates the code for you.
const regex = /\bis.*(this)/gi;
const str = `this is the string and THIS is the word I want`;
let m;
while ((m = regex.exec(str)) !== null) {
// This is necessary to avoid infinite loops with zero-width matches
if (m.index === regex.lastIndex) {
regex.lastIndex++;
}
// The result can be accessed through the `m`-variable.
m.forEach((match, groupIndex) => {
console.log(`Found match, group ${groupIndex}: ${match}`);
});
}
First you have to double backslashes when using the string form of regexes.
Second, you forgot whitespace in your pattern:
var regex = new RegExp("\\S+\\s+(?="+to_search+")", "g");

Categories

Resources