Eyal
Eyal

Reputation: 4763

Remove everything except a certain pattern

I have a log file with lots of strings. I would like to remove everything from this file (find & replace) except any string that starts with: phone= and ended with Digits=1

for example: phone=97212345678&step=1&digits=1

To find that string I am using (phone=.*digits=1) and it works! but I did not manage to find the regex the select everything but this string and to clear them all.

sample file.

Upvotes: 31

Views: 73323

Answers (4)

ozanmut
ozanmut

Reputation: 3234

Let's say you have data like:

"for execution plan [ID = 7420] at 12/06/2018 08:00:00"

you want to extract just [ID = dddd] part from thousands of lines. In Notepad++ press ctrl+h open replace window, check regular expression.

Find what:

.*?(\[ID = \d+\]).*

Replace with:

\1

For your specific string, regex would be:

.*?(phone=.*?digits=1).*

Upvotes: 4

Sandip Ransing
Sandip Ransing

Reputation: 7733

Regex to find the match:

/^phone=.+&digits=1$/

To replace file except match:

/^(?!phone=.+&digits=1$).*/gm

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626709

In order to remove anything but a specific text, you need to use .*(text_you_need_to_keep).* with . matching a newline.

In Notepad++, use

       Find: .*(phone=\S*?digits=1).*
Replace: $1

NOTE: . matches newline option must be checked.

I use \S*? instead of .* inside the capturing pattern since you only want to match any non-whitespace characters as few as possible from phone= up to the closest digits. .* is too greedy and may stretch across multiple lines with DOTALL option ON.

UPDATE

When you want to keep some multiple occurrences of a pattern in a text, in Notepad++, you can use

.*?(phone=\S*?digits=1)

Replace with $1\n. With that, you will remove all the unwanted substrings but those after the last occurrence of your necessary subpattern.

You will need to remove the last chunk either manaully or with

   FIND: (phone=\S*?digits=1).*
REPLACE: $1

Upvotes: 33

York Mak
York Mak

Reputation: 241

If you are using some tools like Notepad++ or EditPlus, you may use the following regex replace:

Find string: ^phone=(\d+&step=1&)digits=1

Replace string: \1

Upvotes: 1

Related Questions