current regex to match multiple subnets delimited by a space rexp = /^([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.[01]?\d\d?|2[0-4]\d|25[0-5]){3}(?:\/[0-2]\d|\/3[0-2])?$(\s(^([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.[01]?\d\d?|2[0-4]\d|25[0-5]){3}(?:\/[0-2]\d|\/3[0-2])?$))*$/)
test string 192.168.2.1/24 192.168.2.1/32
Your regex seems to be broken. You can try this one:
^([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.[01]?\d\d?|2[0-4]\d|25[0-5]){3}(?:\/[0-2]\d|\/3[0-2])?(\s+([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.[01]?\d\d?|2[0-4]\d|25[0-5]){3}(?:\/[0-2]\d|\/3[0-2]))*$
Another option is to parse the string using Javascript and use a simpler regex for each piece. Here is an example:
const s = '192.168.2.1/24 192.168.2.1/32 250.161.23.1/32 0.1.2.1/01';
const pattern = /([01]?\d\d?|2[0-4]\d|25[0-5])(?:\.[01]?\d\d?|2[0-4]\d|25[0-5]){3}(?:\/[0-2]\d|\/3[0-2])/;
const result = s.trim().split(/\s+/).map(e => e.match(pattern) != null).reduce((result, next) => result && next, true);
console.log(result);
This prints:
true
Though you can certainly decompose the string using regex, it might be much easier using code like this:
subnetsString = "192.168.2.1/24 192.168.2.1/32";
subnets = subnetsString.split(" ");
firstSubnet = subnets[0];
ip = firstSubnet.split("/")[0];
console.log(ip); // output: 192.168.2.1
Related
Currently have the following regex to capture all content within square brackets:
regex = /[^[\]]+(?=])/g
Meaning that:
string = "[Foo: Bar] [Biz: Baz]"
string.match(regex)
In JavaScript will return: ["Foo: Bar", "Biz: Baz"]
for a next step, I want to only get the text that follows a the colon. It is safe to assume that on all matches, we'll consistently have a return where each string in the return array matches the above pattern.
I'm sure there's some way to extend my regex to do this at the same time as finding the text within square brackets, but I'm just not sure how to do so. I've tried using some positive look-aheads, but I have no idea where to add them.
Another simple way:
const regex = /\[(\w+)\s*:\s*(\w+)\]/g;
const string = "[Foo: Bar] [Biz: Baz]";
let match;
while(match = regex.exec(string)){
console.log(`Pro: ${match[1]}`)
console.log(`Val: ${match[2]}`)
}
You can add :) or (: ) if you need also to match the space after the colon):
var string = "[Foo: Bar] [Biz: Baz]"
var regex = /[^[\]:]+(?=])/g;
console.log(string.match(regex));
You can try something like this
\[([^:]+:\s*)([^\]]+)
let regex = /\[([^:]+:\s*)([^\]]+)\]/g
let arr = []
let string = "[Foo: Bar] [Biz: Baz]"
while((arr =regex.exec(string))!== null){
console.log(`key -> ${arr[1]}`)
console.log(`val -> ${arr[2]}`)
}
I have this structure of my input data, it is just like JSON but not containing strings. I only need to parse few information from these data
{ .appVersion = "1230"; DisplayStrings = ( A ); customParameters = ( { name = Axes;.......(continues)}'''
the code looks like this, what happens here is that it matches but search until last appearance of semicolon. I tried all non-greedy tips and tricks that I have found, but I feel helpless.
const regex = /.appVersion = (".*"?);/
const found = data.match(regex)
console.log(found)
How can I access value saved under .appVersion variable, please?
You need to escape the . before appVersion since it is a special character in Regex and you can use \d instead of .* to match only digits. If you want just the number to be captured, without the quotes you can take them out of the parentheses.
const regex = /\.appVersion = "(\d+)";/
const found = data.match(regex)
const appVersion = found[1];
const string = '{ .appVersion = "1230"; DisplayStrings = (...(continues)';
const appVersion = string.match(/\.appVersion\s*=\s*"([^"]+)"/)[1];
If that's what you need...
I'm not sure where the format you're trying to parse comes from, but consider asking (making) your data provider return json string, so you could easily invoke JSON.parse() which works in both node and browser environments.
You can try the following:
var data='{ .appVersion = "1230"; DisplayStrings = ( A ); customParameters = ( { name = Axes;.......(continues)}';
const regex = /.appVersion = [^;]*/ //regex test: https://regex101.com/r/urX53f/1
const found = data.match(regex);
var trim = found.toString().replace(/"/g,''); // remove the "" if necessary
console.log(found.toString());
console.log(trim);
Your regex is looking for . which is "any character" in a regex. Escape it with a backslash:
/\.appVersion = ("\d+");/
Don't use .* to capture the value, It's greedy.
You can use something like \"[^\"]* - Match a quote, then Any character except quote, as many time as possible.
try
const regex = \.appVersion = \"([^\"]*)\";
Note that the first dot is should also be quoted, and the spaces should be exactly as in your example.
I have a csv file which has some lines containing :. I need completely remove those lines. This is what I've done so far.
var array = fs.readFileSync('../list/fusion.csv').toString();
var pattern = /^\:/gm;
var best = array.replace(pattern, '');
fs.writeFile('../list/full.csv', best, function (err) {
if (err) return console.log(err);
});
I try to replace : with space. My pattern works in regex101, but when i run code nothing happens.
You can do this way also to remove the line that has :. I've added a demo depicting how to remove the whole line that contains that unnecessary character : in your .csv file
const regex = /^.*(:).*$/gm;
const str = `id,name,age
1,aaboss,11
2,eeboss,18
3,:ddboss,15
4,ccboss,14
:5,aboss,13
6,boss,12
7,boss,100:
8,boss,12
`;
const subst = ``;
// The substituted value will be contained in the result variable
// using replace again to remove the empty lines
const result = str.replace(regex, subst).replace(/(^[ \t]*\n)/gm, "");
console.log(result);
REGEX: https://regex101.com/r/JHeRyl/1
If you mean to remove lines containing : you should specify the m flag to allow ^ to match the beginning of every line rather than just the beginning of the string. Your pattern should also be made to match the entire line rather than just :.
Change:
var pattern = /^\:/g;
to:
var pattern = /^.*?:.*?$/gm;
Suppose I have a sting like this: ABC5DEF/G or it might be ABC5DEF-15 or even just ABC5DEF, it could be shorter AB7F, or AB7FG/H.
I need to create a javascript variable that contains the substring only up to the '/' or the '-'. I would really like to use an array of values to break at. I thought maybe to try something like this.
...
var srcMark = array( '/', '-' );
var whereAt = new RegExp(srcMark.join('|')).test.str;
alert("whereAt= "+whereAt);
...
But this returns an error: ReferenceError: Can't find variable: array
I suspect I'm defining my array incorrectly but trying a number of other things I've been no more successful.
What am I doing wrong?
Arrays aren't defined like that in JavaScript, the easiest way to define it would be with:
var srcMark = ['/','-'];
Additionally, test is a function so it must be called as such:
whereAt = new RegExp(srcMark.join('|')).test(str);
Note that test won't actually tell you where, as your variable suggests, it will return true or false. If you want to find where the character is, use String.prototype.search:
str.search(new RegExp(srcMark.join('|'));
Hope that helps.
You need to use the split method:
var srcMark = Array.join(['-','/'],'|'); // "-|/" or
var regEx = new RegExp(srcMark,'g'); // /-|\//g
var substring = "222-22".split(regEx)[0] // "222"
"ABC5DEF/G".split(regEx)[0] // "ABC5DEF"
From whatever i could understand from your question, using this RegExp /[/-]/ in split() function will work.
EDIT:
For splitting the string at all special characters you can use new RegExp(/[^a-zA-Z0-9]/) in split() function.
var arr = "ABC5DEF/G";
var ans = arr.split(/[/-]/);
console.log(ans[0]);
arr = "ABC5DEF-15";
ans = arr.split(/[/-]/);
console.log(ans[0]);
// For all special characters
arr = "AB7FG/H";
ans = arr.split(new RegExp(/[^a-zA-Z0-9]/));
console.log(ans[0]);
You can use regex with String.split.
It will look something like that:
var result = ['ABC5DEF/G',
'ABC5DEF-15',
'ABC5DEF',
'AB7F',
'AB7FG/H'
].map((item) => item.split(/\W+/));
console.log(result);
That will create an Array with all the parts of the string, so each item[0] will contain the text till the / or - or nothing.
If you want the position of the special character (non-alpha-numeric) you can use a Regular Expression that matches any character that is not a word character from the basic Latin alphabet. Equivalent to [^A-Za-z0-9_], that is: \W
var pattern = /\W/;
var text = 'ABC5DEF/G';
var match = pattern.exec(text);
var position = match.index;
console.log('character: ', match[0]);
console.log('position: ', position);
I want to add a (variable) tag to values with regex, the pattern works fine with PHP but I have troubles implementing it into JavaScript.
The pattern is (value is the variable):
/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is
I escaped the backslashes:
var str = $("#div").html();
var regex = "/(?!(?:[^<]+>|[^>]+<\\/a>))\\b(" + value + ")\\b/is";
$("#div").html(str.replace(regex, "" + value + ""));
But this seem not to be right, I logged the pattern and its exactly what it should be.
Any ideas?
To create the regex from a string, you have to use JavaScript's RegExp object.
If you also want to match/replace more than one time, then you must add the g (global match) flag. Here's an example:
var stringToGoIntoTheRegex = "abc";
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
In the general case, escape the string before using as regex:
Not every string is a valid regex, though: there are some speciall characters, like ( or [. To work around this issue, simply escape the string before turning it into a regex. A utility function for that goes in the sample below:
function escapeRegExp(stringToGoIntoTheRegex) {
return stringToGoIntoTheRegex.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
}
var stringToGoIntoTheRegex = escapeRegExp("abc"); // this is the only change from above
var regex = new RegExp("#" + stringToGoIntoTheRegex + "#", "g");
// at this point, the line above is the same as: var regex = /#abc#/g;
var input = "Hello this is #abc# some #abc# stuff.";
var output = input.replace(regex, "!!");
alert(output); // Hello this is !! some !! stuff.
JSFiddle demo here.
Note: the regex in the question uses the s modifier, which didn't exist at the time of the question, but does exist -- a s (dotall) flag/modifier in JavaScript -- today.
If you are trying to use a variable value in the expression, you must use the RegExp "constructor".
var regex = "(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b";
new RegExp(regex, "is")
I found I had to double slash the \b to get it working. For example to remove "1x" words from a string using a variable, I needed to use:
str = "1x";
var regex = new RegExp("\\b"+str+"\\b","g"); // same as inv.replace(/\b1x\b/g, "")
inv=inv.replace(regex, "");
You don't need the " to define a regular expression so just:
var regex = /(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/is; // this is valid syntax
If value is a variable and you want a dynamic regular expression then you can't use this notation; use the alternative notation.
String.replace also accepts strings as input, so you can do "fox".replace("fox", "bear");
Alternative:
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(value)\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(" + value + ")\b/", "is");
var regex = new RegExp("/(?!(?:[^<]+>|[^>]+<\/a>))\b(.*?)\b/", "is");
Keep in mind that if value contains regular expressions characters like (, [ and ? you will need to escape them.
I found this thread useful - so I thought I would add the answer to my own problem.
I wanted to edit a database configuration file (datastax cassandra) from a node application in javascript and for one of the settings in the file I needed to match on a string and then replace the line following it.
This was my solution.
dse_cassandra_yaml='/etc/dse/cassandra/cassandra.yaml'
// a) find the searchString and grab all text on the following line to it
// b) replace all next line text with a newString supplied to function
// note - leaves searchString text untouched
function replaceStringNextLine(file, searchString, newString) {
fs.readFile(file, 'utf-8', function(err, data){
if (err) throw err;
// need to use double escape '\\' when putting regex in strings !
var re = "\\s+(\\-\\s(.*)?)(?:\\s|$)";
var myRegExp = new RegExp(searchString + re, "g");
var match = myRegExp.exec(data);
var replaceThis = match[1];
var writeString = data.replace(replaceThis, newString);
fs.writeFile(file, writeString, 'utf-8', function (err) {
if (err) throw err;
console.log(file + ' updated');
});
});
}
searchString = "data_file_directories:"
newString = "- /mnt/cassandra/data"
replaceStringNextLine(dse_cassandra_yaml, searchString, newString );
After running, it will change the existing data directory setting to the new one:
config file before:
data_file_directories:
- /var/lib/cassandra/data
config file after:
data_file_directories:
- /mnt/cassandra/data
Much easier way: use template literals.
var variable = 'foo'
var expression = `.*${variable}.*`
var re = new RegExp(expression, 'g')
re.test('fdjklsffoodjkslfd') // true
re.test('fdjklsfdjkslfd') // false
Using string variable(s) content as part of a more complex composed regex expression (es6|ts)
This example will replace all urls using my-domain.com to my-other-domain (both are variables).
You can do dynamic regexs by combining string values and other regex expressions within a raw string template. Using String.raw will prevent javascript from escaping any character within your string values.
// Strings with some data
const domainStr = 'my-domain.com'
const newDomain = 'my-other-domain.com'
// Make sure your string is regex friendly
// This will replace dots for '\'.
const regexUrl = /\./gm;
const substr = `\\\.`;
const domain = domainStr.replace(regexUrl, substr);
// domain is a regex friendly string: 'my-domain\.com'
console.log('Regex expresion for domain', domain)
// HERE!!! You can 'assemble a complex regex using string pieces.
const re = new RegExp( String.raw `([\'|\"]https:\/\/)(${domain})(\S+[\'|\"])`, 'gm');
// now I'll use the regex expression groups to replace the domain
const domainSubst = `$1${newDomain}$3`;
// const page contains all the html text
const result = page.replace(re, domainSubst);
note: Don't forget to use regex101.com to create, test and export REGEX code.
var string = "Hi welcome to stack overflow"
var toSearch = "stack"
//case insensitive search
var result = string.search(new RegExp(toSearch, "i")) > 0 ? 'Matched' : 'notMatched'
https://jsfiddle.net/9f0mb6Lz/
Hope this helps