This question already has answers here:
regex get anything between double curly braces
(3 answers)
Closed 5 days ago.
I would like to get any string between {{ and }} using Regex. for example {{user.email}} should return user.email. To achieve this I have written the below Regex:
const str = '{{user.email}}'
const regExp = /{{([^]*?)}}/g
const variableName = str.match(regExp)
console.log(variableName) // returns ['{{user.email}}'] only not 'user.email'
This is the link for working regexp:
https://regex101.com/r/UdbrT9/1
I'm I missing something ?
Technically that's using lookaheads and lookbehinds. See Lookahead and Lookbehind Zero-Width Assertions.
const str = '{{user.email}}test{{tos}}{{done}}'
const regExp = /(?<=\{\{)(.*?)(?=\}\})/g
const variableName = str.match(regExp);
console.log(variableName)
Your regexp looks correct.
However, the actual "match" is the full string.
What you want is the first captured group (inside parenthesis).
const str = "{{user.email}}";
const regexp = /{{([^]*?)}}/g
const match = regexp.exec(str);
console.log(match[1]); // First captured group in match
Note the use of RegExp::exec() (that contains the full match + the captured group. Unfortunately String::match() does not, it just returns the full match.
Why don't you use replace?
string.replace(/{{|}}/g, '') or replaceAll
Related
This question already has answers here:
Regex to match all instances not inside quotes
(4 answers)
Closed 2 years ago.
I need to split a string using a delimiter character (= in my example) , except if this character is inside quotes or double quotes
I succeed to do it within single quotes using \=+(?=(?:(?:[^']*'){2})*[^']*$) , or within double quotes using \=+(?=(?:(?:[^"]*"){2})*[^"]*$), but not for both, what would be the appropriate RegExp ?
Bonus: if it can also split when the character is not inside character ` , it would be perfect :)
What I need :
Edit: Javascript example to reproduce ( https://jsfiddle.net/cgnorhm0/ )
function splitByCharExceptInsideString(str, delimiterChar) {
// split line by character except when it is inside quotes
const escapedChar = delimiterChar.replace(/[-[\]{}()*+!<=:?./\\^$|#\s,]/g, "\\$&");
const regSplit = new RegExp(escapedChar + `+(?=(?:(?:[^']*'){2})*[^']*$)`);
const splits = str.split(regSplit);
return splits ;
}
const testStr = `image.inside {
sshagent(credentials: ['ssh-creds']) {
env.GIT_SSH_COMMAND="ssh -T -o StrictHostKeyChecking=no"
env.GIT_SSH_COMMAND2='ssh -T -o StrictHostKeyChecking=no'
}
}`;
const delimiterChar = '=';
const splitLs = splitByCharExceptInsideString(testStr,delimiterChar);
console.log(splitLs);
lookahead and lookbehind don't consume character so you can use multiple of them together. you can use
\=+(?=(?:(?:[^"]*"){2})*[^"]*$)(?=(?:(?:[^']*'){2})*[^']*$)(?=(?:(?:[^`]*`){2})*[^`]*$)
Regex Demo
The regex below finds = characters that are not inside `, ", or ' pairs.
const regex = /=(?=.*)(?=(?:'.*?'|".*?"|`.*?`).*?)/;
Behavior with your example:
This question already has answers here:
Changing the RegExp flags
(4 answers)
Closed 3 years ago.
ok, I have a problem here, in my database I store regexPath that made from URL.
I used this package path-to-regex
so I store my converted path to regex as String in the database like this:
let path = "/v1/manager/notification/all"
let regexPath = "/^\/v1\/manager\/notification\/all(?:\/)?$/i"
and I need test() function for checking some condition.
ofcourse test() function need a regex format for checking value is exists in regex.the only way I found in internet for convert string to regex is :
let RegexPattern = new RegExp(regexPath)
but RegExp function consider my i tag as a part of regex him self and it returns something like this:
/"\/^\\\/v1\\\/manager\\\/notification\\\/all\\\/page\\=([^\\=\\\/]+?)(?:\\\/)?$\/i"/
how should I solve this problem?
You need to extract the inner regex and flags before. Here's an example:
const path = "/v1/manager/notification/all"
const regexPath = "/^\/v1\/manager\/notification\/all(?:\/)?$/i"
const separator = regexPath.lastIndexOf('/')
const pattern = regexPath.slice(1, separator)
const flags = regexPath.slice(separator + 1)
const regex = new RegExp(pattern, flags)
console.log('Pattern: ' + pattern)
console.log('Flags: ' + flags)
console.log('Regex: ' + regex)
Per https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp you need to extract the modifiers yourself and pass them in as the second parameter. You will also need to remove the leading and trailing slashes.
new RegExp(pattern[, flags])
This question already has answers here:
Javascript/regex: Remove text between square brackets
(4 answers)
Closed 5 months ago.
In short i need to replace every occurrence of text betweeen brackets including the brackets in a string, and the text to be replaced will be in a variable in Javascript.
A simple regex in a replace method wont work because of the brackets.
Example, replace "[test] [teste] test [hello]" with a variable with the value of "hi".
Output: "hi hi test [hello]"
"[test] [teste] test".replace(/\[.*?\]/g, 'hi')
escape the brackets with "\" and use g flag
edit: removed the i flag and chnaged w to . to handle anything inside brackets
I'm not quite sure what you're looking for but .match will store off the matches in an array and .replace will perform the replace for you.
const regex = /\[.*?\]/g;
var mutable = "[test] [teste] test";
const matches = mutable.match(regex); // Save all matches to an array
mutable = mutable.replace(regex, 'dude'); // Replace matches
console.log(mutable);
console.log(matches);
So, the way i found to do it was to get my variable to be replaced, example:
var test= "[test]",
Then i replaced the brackets in it so it would become "\[test\]", then i used:
var regex = new RegExp(test+"+","gm")
then i used this regex in JS replace method.
This question already has answers here:
match() returns array with two matches when I expect one match
(2 answers)
Closed 5 years ago.
I cant understand why this code snippet return an array on two strings "BEARING" instead of only a string "BEARING. Any ideas?
const cleanedString = "ANGULAR CONTACT (ROLLING) BEARING"
const noun = cleanedString.match(/\b(\w+)$/);
console.log(noun);
You need to use the global /g flag:
const cleanedString = "ANGULAR CONTACT (ROLLING) BEARING"
const noun = cleanedString.match(/\b(\w+)$/g);
console.log(noun);
From String.prototype.match() [MDN]:
If the regular expression does not include the g flag, str.match() will return the same result as RegExp.exec().
It returns an array of 2 which signify
Full Match of the string
String matched in the first capturing group
You can make it a non capturing group by
const cleanedString = "ANGULAR CONTACT (ROLLING) BEARING"
const noun = cleanedString.match(/\b(?:\w+)$/);
console.log(noun);
where ?: signifies that the group would be non capturing
By default match returns the string that matched as the first value.
By putting parens in your regex, you asked for a part of the matched string to be returned (which happens to be the same in this case).
So if your regex had been this:
/^(\w+).*\b(\w+)$/
You would have 3 strings returned
The whole string
ANGULAR
BEARING
This question already has an answer here:
Reference - What does this regex mean?
(1 answer)
Closed 4 years ago.
I'm looking for some assistance with JavaScript/Regex when trying to format a string of text.
I have the following IDs:
00A1234/A12
0A1234/A12
A1234/A12
000A1234/A12
I'm looking for a way that I can trim all of these down to 1234/A12. In essence, it should find the first letter from the left, and remove it and any preceding numbers so the final format should be 0000/A00 or 0000/AA00.
Is there an efficient way this can be acheived by Javascript? I'm looking at Regex at the moment.
Instead of focussing on what you want to strip, look at what you want to get:
/\d{4}\/[A-Z]{1,2}\d{2}/
var str = 'fdfhfjkqhfjAZEA0123/A45GHJqffhdlh';
match = str.match(/\d{4}\/[A-Z]{1,2}\d{2}/);
if (match) console.log(match[0]);
You could seach for leading digits and a following letter.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'],
regex = /^\d*[a-z]/gi;
data.forEach(s => console.log(s.replace(regex, '')));
Or you could use String#slice for the last 8 characters.
var data = ['00A1234/A12', '0A1234/A12', 'A1234/A12', '000A1234/A12'];
data.forEach(s => console.log(s.slice(-8)));
You could use this function. Using regex find the first letter, then make a substring starting after that index.
function getCode(s){
var firstChar = s.match('[a-zA-Z]');
return s.substr(s.indexOf(firstChar)+1)
}
getCode("00A1234/A12");
getCode("0A1234/A12");
getCode("A1234/A12");
getCode("000A1234/A12");
A regex such as this will capture all of your examples, with a numbered capture group for the bit you're interested in
[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})
var input = ["00A1234/A12","0A1234/A12","A1234/A12","000A1234/A12"];
var re = new RegExp("[0-9]*[A-Z]([0-9]{4}/[A-Z]{1,2}[0-9]{2})");
input.forEach(function(x){
console.log(re.exec(x)[1])
});