'How to replace only part of found text?
I have a file with a some comma separated names and some comma separated account numbers.
Names will always be something like Dow, John and numbers like 012394,19862.
Using Notepad++'s "Regex Find" feature, I'd like to replace commas between numbers with pipes |.
Basically :
turn: Dow,John into: Dow,John
12345,09876 12345|09876
13568,08642 13568|08642
I've been using [0-9], to find the commas, but I can't get it to properly leave the number's last digit and replace just the comma.
Any ideas?
Solution 1:[1]
use this regex
(\d),(\d)
and replace it with
$1|$2
OR
\1|\2
Solution 2:[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|
Solution 3:[3]
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$nbackreference 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\Kmakes the regex engine "forget" the text is has matched up to the\Kposition, 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 betweenaand=).
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).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | |
| Solution 3 | Wiktor Stribiżew |

