1

Let's assume the following text

a=1
b=2
x=1
---------
a=1
b=3
c=3
x=2
---------
a=2
b=5
x=3
... and so on, many blocks starting with a=, ending with x= and something in between

I would like to replace the x value with 0 for all blocks where a=1. For this, I search for the following

^(a=1$.*?x=).*$

and replace it with

\10

The problem is, that the first occurence already extends from the first a=1 to the last x=3. It does not stop at the first occurence of x (i.e. x=1)

How can I make it select only from the first a to the x that goes along with this a (i.e. only the first 3 lines, then the 4 lines of the next block, and so on)?

0

4 Answers 4

1

I was almost there... just forgot to make the last .* lazy as well. So the correct search string is

^(a=1$.*?x=).*?$
1
  • Ctrl+H
  • Find what: ^a=1$(?:(?!^a=).)+x=\K\d+
  • Replace with: 0
  • CHECK Match case
  • CHECK Wrap around
  • CHECK Regular expression
  • CHECK . matches newline
  • Replace all

Explanation:

^                   # beginning of line
a=1                 # literally a=1
$                   # end of line
       # Tempered Greedy Token
(?:                 # non capture group
    (?!             # negative lookahead, make sure we haven't:
        ^a=           # a line that begins with a=
    )               # end lookahead
    .               # any character
)+                  # end group may appear 1 or more times
x=                  # literally x=
\K                  # forget all we have seen until this position
\d+                 # 1 or more digitss

Screenshot (before):

enter image description here

Screenshot (after):

enter image description here

2
  • Thank you for the interesting solution. There is definitely more than one way to tackle this problem :-)
    – Thomas
    Jun 24, 2020 at 12:49
  • @Thomas: You're welcome, glad it helps.
    – Toto
    Jun 24, 2020 at 12:50
0

This should do what you are asking for:

Insert into "Find What:" (a=1[^x]*x=)([0-9])

Insert into "Replace With:" \10

I have tested this with the data given and using the following online tool to build the regex query - https://regex101.com/

0

You can try the following:

  • In the Find what box, enter: (^a=1$.*?x=)(\d+)
  • In the Replace with box: ${1}0

IMG:

3
  • Sorry, but that is not entirely correct, either. It replaces the x by a 0, not the text following x=
    – Thomas
    Jun 22, 2020 at 21:06
  • @Thomas you wrote on the OP: "I would like to replace the x value with 0 for all blocks where a=1". Has that changed? or are you replaceing the value of x? Jun 22, 2020 at 21:34
  • @Thomas See edit. Jun 22, 2020 at 21:42

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .