replace one word/number with another word/number on the same line with regular expression
-
hello, I need a little help, please. I have this 2 lines/rows that both contains the number
2002
and the wordMichael
. I want to replace2002
with2012
in each line that containsMichael
.There was a literary and surrealistic magazine edited by André Breton. On March 02, 2002, in Performance Management, by Michael London I get the book.
Its first issue was published on December 14, 2002, in Performance Management book, written by Michael London after his wife get him...
I made a regex, it is almost good, but instead of replacing it, it adds
2012
near2002
. I don’t know what I did wrong. Can anyone help me?FIND:
(^.*)(?=(2002))(.*?)(Michael)(.*?)
REPLACE BY:\12012, \3\4\5
-
@Robin-Cruise said in replace one word/number with another word/number on the same line with regular expression:
(^.)(?=(2002))(.?)(Michael)(.*?)
The way I read your regex it appears that although you think you are capturing 2002 in group 2, as it is inside the positive look ahead that prevents the regex engine actually moving the cursor forward. Then it starts on group 3 which AGAIN captures 2002, hence you write it back.
Just remove the positive look ahead leaving it as (2002). I think that will solve your main issue. I do note that you write a comma back, yet I believe you already captured it so possible some other minor changes also required.
I’m not on a PC to check this myself.
Terry
-
@Terry-R said in replace one word/number with another word/number on the same line with regular expression:
(^.)(?=(2002))(.?)(Michael)(.*?)
thanks
should be:
FIND:
(^.*)(2002)(.*?)(Michael)(.*?)
REPLACE BY:
\12012\3\4\5
-
Thanks for showing what you tried, and what you had success with.
Your final regex works if
2002
appears BEFOREMichael
on a line (or multiple lines as you don’t qualify your usage of.
).This pair seems to correct those deficiencies:
find:
(?-s)^(?=.*?Michael)(.*?20)02
repl:${1}12
-
Hello, @robin-cruise, @Terry-R and All,
Why not this simplified version :
SEARCH
(?-is)2002(?=.*Michael)
REPLACE
2012
Notes :
-
The regex searches for the string
2002
ONLY IF , further on, in current line, the stringMichael
, with that exact case, can be found -
If so, it is replaced with the string
2012
-
In case, the forename
Michael
could be located before the2002
string, here is an improved version taking the two cases in account :-
SEARCH
(?-is)2002(?=.*Michael)|Michael.*\K2002
-
REPLACE
2012
-
Use the
Replace All
button, only !
-
Best Regards,
guy038
P.S. :
Oh…, I’ve just seen the @alan-kilborn version which is really clever as it does not need an alternative ;-))
So, I just added the
(?-i)
modifier, if necessary and the\K
feature to avoid any group :-
SEARCH
(?-is)^(?=.*?Michael).*\K2002
-
REPLACE
2012
-
Use the
Replace All
button, only !
-