Regex delete certain lines - javascript

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;

Related

regex to match multiple subnets delimited by a space

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

Using RegExp to substring a string at the position of a special character

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

Creating a regex to replace each matched character of a string with same character

In my application, I have an alphanumeric string being passed into my function. This string is typically 17 characters, but not always. I'm trying to write a regex that matches all but the last 4 characters in the string, and replaces them with X (to mask it).
For example
Input: HGHG8686HGHG8686H
Output: XXXXXXXXXXXXX686H
The Regex I wrote to perform the replace on the string is as follows
[a-zA-Z0-9].{12}
Code:
const maskedString = string.replace(/[a-zA-Z0-9].{12}/g, 'X');
The issue I'm having is that it's replacing all but the last 4 characters in the string with just that single X. It doesn't know to do that for every matched character. Any ideas?
you can use a function inside replace to do this, something like this will do:
var str = "HGHG8686HGHG8686H"
var regexp = /[a-zA-Z0-9]+(?=....)/g;
var modifiedStr = str.replace(regexp, function ($2) {
return ('X'.repeat($2.length +1));
});
console.log(modifiedStr);
The simple version: (Easier to read)
const maskedString = string.replace(/(.{4})$|(^(..)|(.))/g, 'X\1'); // or X$1
Now using: [a-zA-Z0-9]
const maskedString = string.replace(/([a-zA-Z0-9]{4})$|(^([a-zA-Z0-9]{2})|([a-zA-Z0-9]{1}))/g, 'X\1'); // or X$1
Note: The reason i match on the START PLUS TWO characters is to offset the first match. (The final 4 characters that are appended at the end.)
Look ahead (?=) to make sure there are at least four following characters.
const regex = /.(?=....)/g;
// ^ MATCH ANYTHING
// ^^^^^^^^ THAT IS FOLLOWED BY FOUR CHARS
function fix(str) { return str.replace(regex, 'X'); }
const test = "HGHG8686HGHG8686H";
// CODE BELOW IS MERELY FOR DEMO PURPOSES
const input = document.getElementById("input");
const output = document.getElementById("output");
function populate() { output.textContent = fix(input.value); }
input.addEventListener("input", populate);
input.value = test;
populate();
<p><label>Input: </label><input id="input"></p>
<p>Output: <span id="output"></span></p>
A non-regexp solution:
const test = "HGHG8686HGHG8686H";
function fix(str) {
return 'X'.repeat(str.length - 4) + str.slice(-4);
}
console.log(fix(test));
You will not find String#repeat in IE.
You can achieve using following method:
var str = "HGHG8686HGHG8686H"
var replaced=''
var match = str.match(/.+/)
for(i=0;i<match[0].length-4;i++){
str = match[0][i]
replaced += "X"
}
replaced += match[0].substr(match[0].length-4)
console.log(replaced);

Regex match quotes inside bracket regex

I'm working on a regex that must match only the text inside quotes but not in a comment, my macthes must only the strings in bold
<"love";>
>/*"love"*/<
<>'love'<>
"lo
more love
ve"
I'm stunck on this:
/(?:((\"|\')(.|\n)*?(\"|\')))(?=(?:\/\**\*\/))/gm
The first one (?:((\"|\')(.|\n)*?(\"|\'))) match all the strings
the second one (?=(?:\/\**\*\/)) doesn't match text inside quotes inside /* "mystring" */
bit my logic is cleary wrong
Any suggestion?
Thanks
Maybe you just need to use a negative lookahead to check for the comment end */?
But first, I'd split the string into separate lines
var arrayOfLines = input_str.split(/\r?\n/);
or, without empty lines:
var arrayOfLines = input_str.match(/[^\r\n]+/g);
and then use this regex:
["']([^'"]+)["'](?!.*\*\/)
Sample code:
var rebuilt_string = ''
var re = /["']([^'"]+)["'](?!.*\*\/)/g;
var subst = '<b>$1</b>';
for (i = 0; i < arrayOfLines.length; i++)
{
rebuilt_string = rebuilt_string + arrayOfLines[i].replace(re, subst) + "\r\n";
}
The way to avoid commented parts is to match them before. The global pattern looks like this:
/(capture parts to avoid)|target/
Then use a callback function for the replacement (when the capture group exists, return the match without change, otherwise, replace the match with what you want.
Example:
var result = text.replace(/(\/\*[^*]*(?:\*+(?!\/)[^*]*)*\*\/)|"[^"\\]*(?:\\[\s\S][^"\\]*)*"|'[^'\\]*(?:\\[\s\S][^'\\]*)*'/g,
function (m, g1) {
if (g1) return g1;
return '<b>' + m + '</b>';
});

Use dynamic (variable) string as regex pattern in JavaScript

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

Categories