How to put a space after a comma after a number in a regular expression

Asked 1 years ago, Updated 1 years ago, 69 views

Thank you for your help.
I would like to put a space after the comma after the number.
Therefore, we have specified the following regular expressions:

pattern string:
(\d+),
Search word string:
\1, 

However, in the case of regular expressions like the one above, strings such as 1,2,3,4,5 are fine, but strings such as 1,234 with positioning points are a little inconvenient.
Is there any good way to write?
I use Python as my language, but I'm not particular about it, so I don't mind anything else.
I'm sorry that this is a difficult question to understand, but I'd appreciate it if you could give me some advice.
Thank you for your cooperation.

regular-expression

2022-09-30 21:48

2 Answers

In the first place, how do you distinguish between positioning commas and delimiting commas?
If there are any conditions, I think we should implement them.


2022-09-30 21:48

If you have no choice but to visually distinguish between positioning commas and delimiting commas, it would be easier to replace them individually with a text editor that can replace regular expressions.

If the text has few commas for positioning, it is possible to use the following sample code to list and notify suspicious points.

sample code

import re

US>"src="" 
1,2,3,4,5
12,345th place
,123,456,789
1,23,456 The first , is separated.The second may be the rank.
This isn't 123,4567 either.
1.234567,890 decimal places separated by spaces
""" 
pattern=re.compile(r",(\d+)")

# substitution
result=pattern.subn(r", \1", src)
print(result[0])
Replaced print(f"{result[1]} locations.")

# Simple check of candidates for positioning commas
if(result[1]>0):
    print("Displays the location of the positioning comma candidate and **appropriate text**.")
for i,lin enumerate(src.splitlines()):
    for min pattern.finder(l):
        iflen(m.group(1))) == 3:
            print("{} line {} characters may be positioning commas: {}**{}**{}.format(i+1, m.start()+1, l[:m.start()], l[m.start():m.end()], l[m.end():]))

Run Results


1, 2, 3, 4, 5
12,345th place
, 123, 456, 789
1,23,456 The first , is separated.The second may be the rank.
This isn't 123,4567 either.
1.234567,890 decimal places separated by spaces

I replaced 12 places.
3 lines 3 characters may be positioning commas: 12**,345** positioning
The first character on the fourth line may be a positioning comma: **,123**,456,789
The 5th character in line 4 may be a positioning comma: ,123**,456**,789
The 9th character in line 4 may be a positioning comma: ,123,456**,789**
The 5th line and 5th character may be a positioning comma: 1,23**,456** The 1st, is separated.The second may be the rank.
The 10th character in line 7 may be a positioning comma: 1.234567**, 890** Decimal points separated by spaces


2022-09-30 21:48

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.