RegEx mismatch in node.js [duplicate] - javascript

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');

Related

Get last 2 or 3 elements from path regex

So i currently have a path and i am trying to fetch the last 3;
Test:
/testing/path/here/src/handlebar/sample/colors.txt
/testing/path/here/src/handlebar/testing/another/colors.txt
Regex:
\/([^/]+\/[^/]+\/[^/]+)\.[^.]+$
Result:
handlebar/sample/colors
testing/another/colors
What i want it to do:
sample/colors
testing/another/colors
If there are 2 directories and then the item, it should utilise the 3 and if it contains the word handlebar, it should only be two.
You could just create a group for everything behind handlebar/ like this:
with a named capturing group (subPath group contains wanted value):
/handlebar\/(?<subPath>\S*)\.\S+$/gm
without naming (first group contains wanted value):
/handlebar\/(\S*)\.\S+$/gm
Explanation: This regex matches everything ending with 'handlebar/(...any non white-space chacters 0 to infinite times).(any white-space character 1-inifite times)'. With flags globally and multiline, if you want to check multiple paths within one string separated with a line break e.g.
As you tagged the question with the tag javascript, here is some example code, how to retrieve the value of the regex group
function getSubPath(fullPath = '') {
const regex = /handlebar\/(?<subPath>\S*)\.\S+$/gm
const match = regex.exec(fullPath)
if (match) {
return match.groups.subPath
}
return fullPath // regex.exec did not deliver match
}
getSubPath('/testing/path/here/src/handlebar/sample/colors.txt')
// returns 'sample/colors'
getSubPath('/testing/path/here/src/handlebar/testing/another/colors.txt')
// returns 'testing/another/colors'
without the named group, just read / return match.groups[1] for first capturing group; index 0 is for the full match (which would include the '/handlebars' and the file extension)
I hope you'll get like this.
This is the dynamic tomorrow you can pass as per your required parameters and get result..
<script>
var res = "/testing/path/here/src/handlebar/sample/colors.txt";
var res1 = "/testing/path/here/src/handlebar/testing/another/colors.txt";;
Result = (val, text) => {
var r = val.split(text + '/')[1];
return r.substr(0, r.lastIndexOf('.'));
}
console.log(Result(res, "handlebar"));
console.log(Result(res1, "handlebar"));
</script>
A javascript solution without regex would look like this:
const getTokenizedPath = path => {
const pathArray = path.split('/');
// last element of array looks like "colors.txt" - split by dot and read the first value, removing the extension
pathArray[pathArray.length-1] = pathArray[pathArray.length-1].split('.')[0];
// Remove all elements before the 'handlebar' token and join the remaining values together by '/'.
return pathArray.slice(pathArr2.indexOf('handlebar')+1).join('/');
}
getTokenizedPath('/testing/path/here/src/handlebar/sample/colors.txt');
--- sample/colors.txt
getTokenizedPath('/testing/path/here/src/handlebar/testing/another/colors.txt');
--- testing/another/colors
I guess,
(?!.*handlebar)/([^/]+/[^/]+/[^/]+)\.[^.]+$|/([^/]+/[^/]+)\.[^.]+$
might work OK.
Demo 1
and if lookarounds would be supported,
(?!.*handlebar)(?<=/)[^/]+/[^/]+/[^/]+(?=\.[^.]+$)|$|(?<=/)([^/]+/[^/]+)(?=\.[^.]+$)
Demo 2
would be an option too.
const regex = /(?!.*handlebar)\/([^\/]+\/[^\/]+\/[^\/]+)\.[^.]+$|\/([^\/]+\/[^\/]+)\.[^.]+$/gm;
const str = `/testing/path/here/src/handlebar/sample/colors.txt
/testing/path/here/src/handlebar/testing/another/colors.txt`;
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}`);
});
}
RegEx Circuit
jex.im visualizes regular expressions:
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.

Regex for matching substring in JavaScript using VCS

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}`);
});
}

Problem with extracting multiple segments [duplicate]

This question already has answers here:
How can I get query string values in JavaScript?
(73 answers)
Closed 3 years ago.
I'm trying to capture the bellow parts from the attached log:
aff_lsr?tt_adv_id=806&tt_cid=&tt_adv_sub=b3fff3722fc6b52aedde9b86bb22bf23&tt_time=2016-04-05+16%3A08%3A18&
should capture:
● tt_adv_id
● 806
● tt_adv_sub
● b3fff3722fc6b52aedde9b86bb22bf23
● tt_time
● 2016-04-05+16%3A08%3A18
I have tried to create a regex to extract all strings which start with either “?” “&” or “=” and end with either “=” or “&”
this is the regex I have tried:
(?=[?/&/=]).*?(=)|(?=[=/&])
it ignores all parts between “=” and “&”
so the result i get is :
?tt_adv_id =
&tt_cid=
&tt_adv_sub=
&tt_time =
You can simply use
/[?&=]([^&=]+)/
[?&=] - Match ?, & or =
([^&=]+) - Match anything except & and = one or more time
and than drop off the first character of each match,
let str = "aff_lsr?tt_adv_id=806&tt_cid=&tt_adv_sub=b3fff3722fc6b52aedde9b86bb22bf23&tt_time=2016-04-05+16%3A08%3A18&"
let matched = str.match(/[?&=]([^&=]+)/g).map((v)=>v.substr(1))
console.log(matched)
Maybe, these simple expressions would extract our desired values:
.*(tt_adv_id)=([^&]*)&(?:tt_cid)=(?:[^&]*)&(tt_adv_sub)=([^&]*)&(tt_time)=([^&]*).*
or
(tt_adv_id)=([^&]*)&(?:tt_cid)=(?:[^&]*)&(tt_adv_sub)=([^&]*)&(tt_time)=([^&]*)
The expression is explained on the top right panel of this demo, if you wish to explore further or modify it, and in this link, you can watch how it would match against some sample inputs step by step, if you like.
const regex = /.*(tt_adv_id)=([^&]*)&(?:tt_cid)=(?:[^&]*)&(tt_adv_sub)=([^&]*)&(tt_time)=([^&]*).*/gm;
const str = `aff_lsr?tt_adv_id=806&tt_cid=&tt_adv_sub=b3fff3722fc6b52aedde9b86bb22bf23&tt_time=2016-04-05+16%3A08%3A18&
`;
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}`);
});
}

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