Delete line starting with a word in Javascript using regex - javascript

I have few lines on text.
Random 14637547548546546546sadas3463427
Random 1463754754854654654sadsa63463427
Macroflex 1463754754854654sada65463463427
Random 146375475485465465sdas463463427
Random 1463754754854654fdasf65463463427
I would like to find a line what starts with Macroflex (in this case) and replace/delete it. This is what I have so far... I have tried over and over with regex, but it makes my head hurt. Can anyone give me an advice?
var myRegex = data.replace('Macroflex', '')

You have to replace to the end of the line:
var myRegex = data.replace(/^Macroflex.*$/gm, '');
Note that you have to specify the m flag to let ^ and $ work with newlines.
If you want to remove the newline after the line, you can match it:
var myRegex = data.replace(/^Macroflex.*\n?/gm, '');
This works since . does not match newlines.
The /g flag enables removing multiple occurrences of the line.

Related

Javascript - Replace text beetwen special characters

I'm trying to replace everything between special characters of a string in Javascript.
var text = "Hello,\n>> Someone lalalala\nMore Text\n<<";
I've tried the following code:
var newText = text.replace(/>>.*<</, ">>Some other text<<");
But at the end it actually returns the text variable.
I'd appreciate some thoughts about this. Thanks.
Regexes are "greedy", meaning they'll try to match the longest substring possible. Since .* means literally any character, it's going to include your delimiter << as well. Thus, .* reaches all the way to the end of your string, and then it can't find << after that, so the match will fail. You have to exclude it in your expression:
text.replace(/>>[^<]*<</, ">>Some other text<<");
The problem is that '.' does not match new lines. Using this answer:
var text = "Hello,\n>> Someone lalalala\nMore Text\n<<";
var newText = text.replace(/>>[\s\S]*<</m, ">>Some other text<<");
console.log(newText);

I need some help for a specific regex in javascript

I try to set a correct regex in my javascript code, but I'm a bit confused with this. My goal is to find any occurence of "rotate" in a string. This should be simple, but in fact I'm lost as my "rotate" can have multiple endings! Here are some examples of what I want to find with the regex:
rotate5
rotate180
rotate-1
rotate-270
The "rotate" word can be at the begining of my string or at the end, or even in the middle separated by spaces from other words. The regex will be used in a search-and-replace function.
Can someone help me please?
EDIT: What I tried so far (probably missing some of them):
/\wrotate.*/
/rotate.\w*/
/rotate.\d/
/\Srotate*/
I'm not fully understanding the regex mechanic yet.
Try this regex as a start. It will return all occurrences of a "rotate" string where a number (positive or negative) follows the "rotate".
/(rotate)([-]?[0-9]*)/g
Here is sample code
var aString = ["rotate5","rotate180","rotate-1","some text rotate-270 rotate-1 more text rotate180"];
for (var x = 0; x < 4; x++){
var match;
var regex = /(rotate)([-]?[0-9]*)/g;
while (match = regex.exec(aString[x])){
console.log(match);
}
}
In this example,
match[0] gives the whole match (e.g. rotate5)
match[1] gives the text "rotate"
match[2] gives the numerical text immediately after the word "rotate"
If there are multiple rotate stings in the string, this will return them all
If you just need to know if the 'word' is in the string so /rotate/ simply will be OK.
But if you want some matching about what coming before or after the #mseifert will be good
If you just want to replace the word rotate by another one
you can just use the string method String.replace use it like var str = "i am rotating with rotate-90"; str.repalace('rotate','turning')'
WHy your regex doesnt work ?
/\wrotate.*/
means that the string must start with a caracter [a-zA-Z0-9_] followed by rotate and another optional character
/rotate.\w*/
meanse rotate must be followed by a character and others n optional character
...............
Using your description:
The "rotate" word can be at the beginning of my string or at the end, or even in the middle separated by spaces from other words. The regex will be used in a search-and-replace function.
This regex should do the work:
const regex = /(^rotate|rotate$|\ {1}rotate\ {1})/gm;
You can learn more about regular expressions with these sites:
http://www.regular-expressions.info
regex101.com and btw here is an example using your requirements.

Regex: strip out if not "OBX"

I have data like this:
MSH|1|data1|data2|data3
PID|1|data5|data6|data7
PVI|1|data2|data2|data2
OBX|1|data0|data4|data9
OBX|2|data8|data8|data9
OBX|3|data1|data1|data1
I am trying regex to strip out any lines that don't start with OBX. Here's what I have so far:
message = message.replace(/^(?!OBX).+/g, '');
Even though I have /g it only triggered on the first. Is there something else I'm missing?
Since you are using anchor ^ in your regex, you will need to use m flag (MULTILINE):
message = message.replace(/^(?!OBX).+/gm, '');
Without m modifier your regex will match ^ only at the start of very first line instead of matching before every line.
RegEx Demo

Why do these JavaScript regular expression capture parenthesis snag entire line instead of the suffixes appended to a word?

Can someone please tell me WHY my simple expression doesn't capture the optional arbitrary length .suffix fragments following hello, matching complete lines?
Instead, it matches the ENTIRE LINE (hello.aa.b goodbye) instead of the contents of the capture parenthesis.
Using this code (see JSFIDDLE):
//var line = "hello goodbye"; // desired: suffix null
//var line = "hello.aa goodbye"; // desired: suffix[0]=.aa
var line = "hello.aa.b goodbye"; // desired: suffix[0]=.aa suffix[1]=.b
var suffix = line.match(/^hello(\.[^\.]*)*\sgoodbye$/g);
I've been working on this simple expression for OVER three hours and I'm beginning to believe I have a fundamental misunderstanding of how capturing works: isn't there a "cursor" gobbling up each line character-by-character and capturing content inside the parenthesis ()?
I originally started from Perl and then PHP. When I started with JavaScript, I got stuck with this situation once myself.
In JavaScript, the GLOBAL match does NOT produce a multidimensional array. In other words, in GLOBAL match there is only match[0] (no sub-patterns).
Please note that suffix[0] matches the whole string.
Try this:
//var line = "hello goodbye"; // desired: suffix undefined
//var line = "hello.aa goodbye"; // desired: suffix[1]=.aa
var line = "hello.aa.b goodbye"; // desired: suffix[1]=.aa suffix[2]=.b
var suffix = line.match(/^hello(\.[^.]+)?(\.[^.]+)?\s+goodbye$/);
If you have to use a global match, then you have to capture the whole strings first, then run a second RegEx to get the sub-patterns.
Good luck
:)
Update: Further Explanation
If each string only has ONE matchable pattern (like var line = "hello.aa.b goodbye";)
then you can use the pattern I posted above (without the GLOBAL modifier)
If a sting has more than ONE matchable pattern, then look at the following:
// modifier g means it will match more than once in the string
// ^ at the start mean starting with, when you wan the match to start form the beginning of the string
// $ means the end of the string
// if you have ^.....$ it means the whole string should be a ONE match
var suffix = line.match(/^hello(\.[^.]+)?(\.[^.]+)?\s+goodbye$/g);
var line = 'hello.aa goodbye and more hello.aa.b goodbye and some more hello.cc.dd goodbye';
// no match here since the whole of the string doesn't match the RegEx
var suffix = line.match(/^hello(\.[^.]+)?(\.[^.]+)?\s+goodbye$/);
// one match here, only the first one since it is not a GLOBAL match (hello.aa goodbye)
// suffix[0] = hello.aa goodbye
// suffix[1] = .aa
// suffix[2] = undefined
var suffix = line.match(/hello(\.[^.]+)?(\.[^.]+)?\s+goodbye/);
// 3 matches here (but no sub-patterns), only a one dimensional array with GLOBAL match in JavaScript
// suffix[0] = hello.aa goodbye
// suffix[1] = hello.aa.b goodbye
// suffix[2] = hello.cc.dd goodbye
var suffix = line.match(/hello(\.[^.]+)?(\.[^.]+)?\s+goodbye/g);
I hope that helps.
:)
inside ()
please do not look for . and then some space , instead look for . and some characters and finally outside () look for that space
A repeated capturing group will only capture the last iteration. Put a capturing group around the repeated group to capture all iterations.
var suffix = line.match(/^hello((\.[^\.]*)*)\sgoodbye$/g);
if (suffix !== null)
suffix = suffix[1].match(/(\.[^\.\s]*)/g)
and I recommand regex101 site.
Using the global flag with the match method doesn't return any capturing groups. See the specification.
Although you use ()* it's only one capturing group. The * only defines that the content has to be matched 0 or more time before the space comes.
As #EveryEvery has pointed out you can use a two-step approach.

Javascript regex for hashtag with number only

I want to match these kind of hashtag pattern #1, #4321, #1000 and not:
#01 (with leading zero)
#1aa (has alphabetical char)
But special character like comma, period, colon after the number is fine, such as #1.. Think of it as hashtag at the end of the sentence or phrase. Basically treat these as whitespace.
Basically just # and a number.
My code below doesn't meet requirement because it takes leading zero and it has an ugly space at the end. Although I can always trim the result but doesn't feel it's the right way to do it
reg = new RegExp(/#[0-9]+ /g);
var result;
while((result = reg.exec("hyha #12 gfdg #01 aa #2e #1. #101")) !== null) {
alert("\"" + result + "\"");
}
http://jsfiddle.net/qhoc/d3TpJ/
That string there should just match #12, #1 and #101
Please help to suggest better RegEx string than I had. Thanks.
You could use a regex like:
#[1-9]\d*\b
Code example:
var re = /#[1-9]\d*\b/g;
var str = "#1 hyha #12 #0123 #5 gfdg #2e ";
var matches = str.match(re); // = ["#1", "#12", "#5"]
This should work
reg = /(#[1-9]\d*)(?: |\z)/g;
Notice the capturing group (...) for the hash and number, and the non capturing (?: ..) to match the number only if it is followed by a white space or end of string. Use this if you dont want to catch strings like #1 in #1.. Otherwise the other answer is better.
Then you have to get the captured group from the match iterating over something like this:
myString = 'hyha #12 gfdg #01 aa #2e #1. #101';
match = reg.exec(myString);
alert(match[1]);
EDIT
Whenever you are working with regexps, you should use some kind of tool. For desktop for instance you can use The regex coach and online you can try this regex101
For instance: http://regex101.com/r/zY0bQ8

Categories