How do I replace text with a linebreak using regular expressions - regex

I have written a program that searches for 'opens' without matching 'closes' in a target file. It produces an output like this:
open
close
open
open
close
In this example here the second 'open' is not immediately followed by a matching 'close', so I consider that an error. My text-editor (editpad) has a regular-expression search/replace feature, which I would like to use to get rid of all correct pairs, so I can notice easily the incorrect situations. I tried replacing the following
open\r\nclose
I thought that this would match the two words and the line-break between them (I'm using Windows). This did not work.
Does anyone have an idea why it didn't?

If you select the Regex mode, your regex will work, but I also suggest making \r optional by appending ? after it to support LF endings, too:
open\r?\nclose
See the screenshot with settings and proof it works in EditPad:

Related

Find new lines in Adobe Brackets

I'm trying to do a find and replace on a file to get rid of line breaks using Adobe Brackets. However, when I enter \n in the search field, even with Regular Expression turned on, it says No results. Is there a way to find newlines within Brackets?
You could try this:
(\r\n|\r|\n)

Global find and replace with newline in Visual Studio Code

Suppose I want to remove all lines matching a regex in my project. Is there a way to do that?
Using the global find and replace function with regexes enabled I've tried:
Replace foo|bar with an empty string. This doesn't work because it leaves the line there with an empty string. I want the newline removed.
Replace (foo|bar)\n with an empty string. This doesn't actually match anything.
Replace (foo|bar)$ with an empty string. Again, doesn't match anything.
Any ideas?
Edit: It seems like some of my files have Windows line endings so (foo|bar)\r?\n does match. However when you replace it with an empty string it actually still leaves the line endings there.
Here's a test case:
a
foo
b
It should end up like this:
a
b
Not like this:
a
b
foo\n^ and (foo|bar)\n^ both work.
I just tested in my vs code - and you leave the replacement string blank
Yes, it is possible to remove entire lines with the search-across-files feature.
I'm guessing the original problem was due to a bug or otherwise unwanted behavior in an older version of VSCode. With VSCode 1.37.1, so long as the \n is included in the regex, the line is removed. In particular, the regex (foo|bar)\n, described in the original question as not working, now works fine.
Before:
After pressing the "Replace All" button:
Related observations:
This same regex works even if I set the file line endings to CRLF.
Appending ^ makes no difference. That's a bit surprising, but perhaps "after newline" counts as "beginning of line".
Appending $ causes the regex to not match anything. That is quite surprising given the behavior of ^.
I looked through the search configuration settings, but nothing seemed like it could affect this.

Deleting every 2nd line from a file using Notepad++

I am looking for some regex help.
I have a textfile, nothing super important but I would like to delete every second line from it - I have tried following this guide: Delete every other line in notepad++
However I just can't get it to work, is the regex I am using ok? I am noob with regex
Find:
([^\n]*\n)[^\n]*\n
Replace with:
$1
No matter what I try (mouse position at the beginning, ctrl+a and Replace All) I just can't get it to work. I appreciate any help.
I've put the regex into here: http://regexpal.com/ and if I remove the final \n it highlights the individual rows.
Make sure you select regular expression for the search mode...
Also, you may want to make that final newline optional. In the case that there are an even number of lines and you do not have a trailing newline, it won't remove the last line.
([^\n]*\n)[^\n]*\n?
Update:
See how Windows handle new lines with \r\n instead of just \n. Try updating the expression to take this into account:
([^\r\n]*[\r\n]+)[^\r\n]*[\r\n]*
Final Update:
Thanks to #zx81, I now know that N++ uses PCRE so \R can be used for unicode newline characters. However [^\R] won't work (this looks for anything except R literally), so you will need to keep [^\r\n]. This can be simplified as:
([^\r\n]*\R)[^\r\n]*\R?

How do I escape comma in WMIC inside like string

I wish to be able to run a query like the following:
wmic path Win32_Service where "DisplayName like 'FooBarService % (X, Y)'" get *
But, it doesn't work because of the comma inside the like string. The error I get is "Invalid Verb." I tried escaping it with a backslash, and I tried escaping it using brackets as underscores are meant to be escaped, and both resulted in the "Invalid Verb." error.
As a less-than-ideal workaround, I can replace the commas with underscores, and it works, but the underscore will match any single character rather than just the comma, so I'd rather find a way to escape the commas.
Is there a way to escape the comma like in this example?
One way I have found to include a comma in the like clause is to place the entire where expression in parentheses. Unfortunately, I also found that this means I cannot include a close paren in the string at the same time (but an open paren is okay). I experimented with the /trace:on option to see what was going on under the covers a little bit and it helped me find a couple things the program accepts:
Here is an example I got to work with a comma, but it apparently cannot contain a close paren:
C:\> wmic /trace:on path Win32_Service where (Description like '%(%, %') get DisplayName
And here is an example I got to work with both open and close parentheses, but apparently it cannot contain a comma (obviously, this is quite similar to your original example):
C:\> wmic /trace:on path Win32_Service where "Description like '%(TAPI)%'" get DisplayName
It seems like the parser just isn't complex enough to handle these cases, but with tracing on, you can see the WMI Win32 functions that it uses, so maybe you could write your own program that uses the functions directly. I think IWbemServices::ExecQuery is capable of what you're looking to do.

Multiline Regular Expression search and replace!

I've hit a wall. Does anybody know a good text editor that has search and replace like Notepad++ but can also do multi-line regex search and replace? Basically, I am trying to find something that can match a regex like:
search oldlog\(.*\n\s+([\r\n.]*)\);replace newlog\(\1\)
Any ideas?
Notepad++ can now handle multi line regular expressions (just update to the latest version - feature was introduced around March '12).
I needed to remove all onmouseout and onmouseover statements from an HTML document and I needed to create a non-greedy multi line match.
onmouseover=.?\s*".*?"
Make sure you check the: [ ] . matches newline checkbox if you want to use the multi line match capability.
EditPad Pro has better regex capabilities than any other editor I've ever used.
Also, I suspect you have an error in your regex — [\r\n.] will match only carriage returns, newlines, and full stops. If you're trying to match any character (i.e. "dot operator plus CR and LF), try [\s\S] instead.
My personal recommendation is IDM Computing's UltraEdit (www.ultraedit.com) - it can do regular expressions (both search and replace) with Perl, Unix and UltraEdit syntax. Multi-line matching is one of the capabilities in Perl regex mode in it.
It also has other nice search capabilities (e.g search in specific character column range, search in multiple files, search history, search favorites, etc...)
(source: ultraedit.com)
The Zeus editor can do multi-line search and replace.
I use Eclipse, which is free and that you may already have if you are a developer. '\R' acts as platform independent line delimiter. Here is an example of multi-line search:
search:
\bibitem.(\R.)?\R?{([^{])}$\R^([^\].[^}]$\R.$\R.)
and replace:
\defcitealias{$2}{$3}
I'm pretty sure Notepad++ can do that now via the TextFX plugin (which is included by default). Hit Control-R in Notepad++ and have a play.
TextPad has good Regex search and replace capabilities; I've used it for a while and am pretty happy with it.
From the Features:
Powerful search/replace engine using
UNIX-style regular expressions, with
the power of editor macros. Sets of
files in a directory tree can be
searched, and text can be replaced in
all open documents at once.
For more options than you could possibly need, check out "Notepad++ Alternatives" at AlternativeTo.net.
you can use Python Script plugin for Multiline Regular Expression search and replace!
- http://npppythonscript.sourceforge.net/docs/latest/scintilla.html?highlight=pymlreplace#Editor.pymlreplace
# This example replaces any <br/> that is followed by another on the next line (with optional spaces in between), with a single one
editor.pymlreplace(r"<br/>\s*\r\n\s*<br/>", "<br/>\r\n")
I use Notepad++ all the time but it's Regex has alway been a bit lacking.
Sublime Text is what you want.
EditPlus does a good job at search/replace using regex (including multiline)
You could use Visual Studio. Download Express for free if you don't have a copy.
VS's regex is non-standard, so you'd have to use \n:b+[\r\n] instead.
The latest version of UltraEdit has multiline find and replace w/ regex support.
Or if you're OK with using a more specialized regular expression tool for this, there's Regex Hero. It has the side benefit of being able to do everything on the fly. In other words, you don't have to click a button to test your regular expression because it's automatically tested after every keypress.
Personally, I'd use UltraEdit if I'm looking to replace text in multiple files. That way I can just select the files to replace as a batch and click Replace. But if I'm working with a single text file and I'm in need of writing a more complex regular expression then I'd paste it into Regex Hero and work with it there. That's because Regex Hero can save time when you see everything happen in real-time.
ED for windows has two versions of regex, three sorts of cut and paste (selection, lines or blocks, AND you can shift from one to the next (unlike ultra edit, which is clunky at best) with just a mouse click while you are highlighting -- no need to pull down a menu. The sheer speed of getting the job done is incredible, like reading on a Kindle, you don't have to think about it.
You can use a recent version of Notepad++ (Mine is 6.2.2).
No need to use the option ". match newline" as suggested in another answer. Instead, use the adequate regular expression with ^ for "begin of line" and $ for "end of line". Then use \r\n after the $ for a "new line" in a dos file (or just \n in a unix file as the carriage return is mainly used for dos/windows text file):
Ex.: to remove all lines starting with tags OBJE after a line starting with a tag UID (from a gedcom file - used in genealogy), I did use the following search regex:
^UID (.*)$\r\n^(OBJE (.*)$\r\n)+
And the following replace value:
UID \1\r\n
This is matching lines like this:
UID 4FBB852FB485B2A64DE276675D57A1BA
OBJE #M4#
OBJE #M3#
OBJE #M2#
OBJE #M1#
and the output of the replacement is
UID 4FBB852FB485B2A64DE276675D57A1BA
550 instances have been replaced in less than 1 sec. Notepad++ is really efficient!
Otherwise, to validate a Regular expression I like to use the .Net RegEx Tester (http://regexhero.net/tester/). It's really great to write and test on the fly a Reg Ex...
PS.: Also, you can use [\s\S] in your regex to match any character including new lines. So, if you look for any block of "multi-line" text starting with "xxx" and ending with "abc", the following Regex will be fine:^xxx[\s\S]*?abc$ where "*?" is to match as less as possible between xxx and abc !!!