Reputation: 3710
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?
Upvotes: 29
Views: 39100
Reputation: 627468
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
(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)(?<=a =)\d+
and replace with 500
(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)a =\K\d+
and replace with 500
(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 match a =
even if there are any zero or more horizontal whitespaces between a
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).
Upvotes: 2
Reputation:
(?<=\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|
Upvotes: 3
Reputation: 5443
Search for ([0-9]),
and replace it with \1|
. Does that work?
Upvotes: 38