How to replace only part of found text?
use this regex
(\d),(\d)
and replace it with
$1|$2
OR
\1|\2
(?<=\d),
should work. Oddly enough, this only works if I use replace all, but not if I use replace single. As an alternative, you can use (\d),
and replace with $1|
Search for ([0-9]),
and replace it with \1|
. Does that work?
General thoughts about replacing only part of a match
In order to replace a part of a match, you need to either 1) use capturing groups in the regex pattern and backreferences to the kept group values in the replacement pattern, or 2) lookarounds, or 3) a \K
operator to discard left-hand context.
So, if you have a string like a = 10
, and you want to replace the number after a =
with, say, 500
, you can
- find
(a =)\d+
and replace with\1500
/${1}500
(if you use$n
backreference syntax and it is followed with a digit, you should wrap it with braces) - find
(?<=a =)\d+
and replace with500
(since(?<=...)
is a non-consuming positive lookbehind pattern and the text it matches is not added to the match value, and hence is not replaced) - find
a =\K\d+
and replace with500
(where\K
makes the regex engine "forget" the text is has matched up to the\K
position, making it similar to the lookbehind solution, but allowing any quantifiers, e.g.a\h*=\K\d+
will matcha =
even if there are any zero or more horizontal whitespaces betweena
and=
).
Current problem solution
In order to replace any comma in between two digits, you should use lookarounds:
Find What: (?<=\d),(?=\d)
Replace With: |
Details:
(?<=\d)
- a positive lookbehind that requires a digit immediately to the left of the current location,
- a comma(?=\d)
- a positive lookahead that requires a digit immediately to the right of the current location.
See the demo screenshot with settings:
See the regex demo.
Variations:
Find What: (\d),(?=\d)
Replace With: \1|
Find What: \d\K,(?=\d)
Replace With: |
Note: if there are comma-separated single digits, e.g. 1,2,3,4
you can't use (\d),(\d)
since this will only match odd occurrences (see what I mean).