2

Im trying to use the following regex to search and replace in multiple files in notepad++

([^\n]*)(state="1")([^\n]*)*.

This searches and finds state="1" in the first line of each file and works fine.

However, when I try to replace state="1" using:

Replace with: $1 state="5"

it cuts off the rest of the line.

I thought that it might be possible to get the rest of the line using:

Replace with: $1 state="5" $2

However, $2 doesnt seem to exist as a variable.

Is there some way to attach the rest of the line into variable $2?

Cheers

Heres an image to show how (?=\A[^\n]*)state="1" is not working

Ive updated my version of notepad++ and everything notworking

1 Answer 1

3

Each capture group, (…), is assigned a number, so $2 represents the second capture group, (state="1"). The remainder of the line is captured in $3.

Either remove the capture group around state="1":

([^\n]*)state="1"([^\n]*)*.

Or use $3:

Replace with: $1 state="5" $3

Also, given the simplicity of the task, I don't see why you couldn't just search for state="1" and replace with state="5". There doesn't seem to be any need for regular expressions here.


Update There's nothing in the pattern listed so far which limits the result to only matching strings on the first line. If you need that I'd recommend using a pattern like this:

(?=\A[^\n]*)state="1"

With these settings:

screenshot


Update There seems to be some strange behavior with the \A (beginning of text) anchor inside the lookbehind. Removing from the lookbehind seems to work. Try this pattern:

\A([^\n]*)state="1"

And replace with:

$1state="5"

All the other settings should be fine.

Sign up to request clarification or add additional context in comments.

8 Comments

Its really strange, when I try to replace with $3 in a file that is opened in notepad++ it replaces the first line correctly, but when I try to do it in multiple files, it replaces every occurance (not just those on the first line)
hmmn strange, (?=\A[^\n]*)state="1" this regex doesnt seem to find any of the occurrances of state="1"
@Ke. I tested it out and it seems to work. You might want to try enabling 'Wrap around' if you're testing it within a single file.
Its weird it just says "cant find the text (?=\A[^\n]*)state="1"" :/ all my settings are exactly the same as yours, and tried word wrap too
@Ke. Can you show a short sample of the kind of file you're working with? I tested using a file which simply had state="1" repeated on 3 separate lines.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.