A regular or grep regular expression matches two strings that are almost the same

I look in our code for something that is very similar:

#$foo="bar";
$foo="baz";

Problems:

  • I do not know the name of the variable
  • I do not know which line is really commented out.
  • I really can't correctly write multi-line regex.

My initial attempt was ack /\$(.\*)=.\*$\$($1)=/

I prefer ack usually for grepping code, but I am not against using grep either. JWZ probably thinks that I already have more than 2 problems.

+3
source share
3 answers

Neither grep nor ack will process more than one line at a time.

+6
source

, :

^#\$(\w+)=.*?\$(\1)=

// [x] ^$ match at line breaks
// [x] Dot matches all

grep .

0

This might work:

^#?(\$\w+)\s*=.*[\r\n]+#?\1\s*=.*$

Explanation:

^            start of line
#?           optional comment
(\$\w+)      $, followed by variable name, captured into backreference no. 1
\s*          optional whitespace
=            =
.*           any characters except newline
[\r\n]+      one or more newlines (\r thrown in for safety)
#?           optional comment
\1           same variable name as in the last line
\s*=.*       as above
$            end of line

This does not verify that exactly one of the lines is commented out (it will also match if neither, nor both). If this is a problem, let me know.

I don't know if grep can match multiple lines in one regex; any tool you use should be set to ^/$match start / end of line mode (instead of beginning / end of line).

0
source

Source: https://habr.com/ru/post/1768055/


All Articles