Regex NodeJS Javascript not applying - javascript

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/

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 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 for parsing multiple conditions for groups

I am trying to split string in 3 different parts with regex.
I can only get function parameters from string but i also want to other parts of the string
const regex = /(\(.*?\))+/g;
const sampleString = 'collection.products(take:12|skip:16)';
const result = sampleString.match(regex)
It gives me (take:12|skip:16)
But i also want to get collection and products
Expected result in match
collection
products
take:12|skip:16
Here, we can alter two expressions together:
(\w+)|\((.+?)\)
which group #1 would capture our desired words (\w+) and group #2 would capture the desired output in the brackets.
const regex = /(\w+)|\((.+?)\)/gm;
const str = `collection.products(take:12|skip:16)`;
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}`);
});
}
Demo
RegEx Circuit
jex.im visualizes regular expressions:
You can split the string on . and (\(.*?\))+ and then use reduce to get values in desired format
const sampleString = 'collection.products(take:12|skip:16)';
const result = sampleString.split(/\.|(\(.*?\))+/).reduce((op,inp) => {
if(inp){
inp = inp.replace(/[)(]+/g,'')
op.push(inp)
}
return op
},[])
console.log(result)
This splits on what you want.
const sampleString = 'collection.products(take:12|skip:16)';
const result = sampleString.split(/[.()]*([^.()]+)[.()]*/).filter(function (el) {return el != "";});
console.log(result)

I need to write Regx for text field validation, which start with either 'iqn.yyyy-mm.com.' or 'eqn.'

I need to write Regx for text field validation, which start with either 'iqn.yyyy-mm.com.' or 'eqn.'
After this any number of character or numeric value is allowed
Here 'yyyy-mm' is year and month.
If we are just validating the year and month and before and after chars are OK, then this expression might work:
.+\.[\d]{4}-[\d]{2}\..+
If we wish to add more constraints, we can surely do so by modifying these two .+ in the start and end of string. We can also add start and end chars, if necessary.
const regex = /.+\.[\d]{4}-[\d]{2}\..+/gm;
const str = `iqn.2019-10.com
eqn.2019-10.com
eqn.209-10.com`;
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}`);
});
}
DEMO
RegEx
If this expression wasn't desired, it can be modified/changed in regex101.com.
RegEx Circuit
jex.im visualizes regular expressions:
If you mean is "either 'iqn.yyyy-mm.com.' or 'eqn.'":
pattern = new RegExp('/^(iqn\.\d{4}-\d{2}\.com\.)|(eqn\.)$/');
var str = 'iqn.2019-05.com.';
pattern.test(str); // -> true
var str = 'eqn';
pattern.test(str); // -> true
var str = 'anything else';
pattern.test(str); // -> false
or, if you mean is "either 'iqn.yyyy-mm.com.' or 'eqn.yyyy-mm.com.'":
pattern = new RegExp('/^[ie]qn\.\d{4}-\d{2}\.com\.$/');
var str = 'iqn.2019-05.com.';
pattern.test(str); // -> true
var str = 'eqn.2019-05.com.';
pattern.test(str); // -> true
var str = 'anything else';
pattern.test(str); // -> false
I think this should work :
^[ie]qn\.(?:\d{4}-\d{2}\.\w{2,6})?\.?.+$
Regex101 Link here : Link Here

Getting string parameters using regex

I'm trying to get a regex that can extract data from
BAYARPLN ke 116160029354, SUKSES. Hrg: 84.822. SN: TGK IMUM M SAMIN/R1/450/MAR,APR/Rp.89222/Adm6000/977-1071/047421CA414149E5CEC5. Saldo: 7
and I want to find this value like this...
977-1071
I tried to using parameter regex link this
"/(Adm6000)([^\7]+)/"
But I cant find the string regex 977-1071. Can I ask for help for this?
Did you try like this? see regex https://regex101.com/r/tccJ42/1
const regex = /\d+\-\d+/g; //use \d{3}\-\d{4} if you've digit limit
const str = `BAYARPLN ke 116160029354, SUKSES. Hrg: 84.822. SN: TGK IMUM M SAMIN/R1/450/MAR,APR/Rp.89222/Adm6000/977-1071/047421CA414149E5CEC5. Saldo: 7`;
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}`);
});
}
If you want to match 977-1071 after /Adm6000/ you could first match /Adm6000/ and then capture in a group not a forward slash one or more times ([^/]+)
\/Adm6000\/([^/]+)
Your value 977-1071 will be in captured group 1:
const regex = /Adm6000\/([^/]+)/;
const str = `BAYARPLN ke 116160029354, SUKSES. Hrg: 84.822. SN: TGK IMUM M SAMIN/R1/450/MAR,APR/Rp.89222/Adm6000/977-1071/047421CA414149E5CEC5. Saldo: 7`;
let match = regex.exec(str);
console.log(match[1]);

Categories

Resources