A way to go is to match the parts around the comma and then remove it:
var input = '124,000 km';
input.replace(/(\d+),(\d+\s?km)/g, '
2');
Answer from gion_13 on Stack OverflowA way to go is to match the parts around the comma and then remove it:
var input = '124,000 km';
input.replace(/(\d+),(\d+\s?km)/g, '
2');
For a trimmed list of numbers each on its own line, this works for me:
(\d*),(\d+)/(
2)
Note that the global flag should be active so that the regex keeps on going if there are multiple groups of comma separated digits.
For these values:
1
10
100
1000
1,000
10,000
10000
1,200,000,000,000,999
the regex yields
1
10
100
1000
1000
10000
10000
1200000000000999
Tested here.
regex - remove comma from a digits portion string - Stack Overflow
c# - Removing commas from numbers with .NET regex - Stack Overflow
Replacing space and comma from a string using regex
remove comma separation from the specific number from JS
public static void main(String args[]) throws IOException
{
String regex = "(?<=[\\d])(,)(?=[\\d])";
Pattern p = Pattern.compile(regex);
String str = "John loves cakes and he always orders them by dialing \"989,444 1234\". Johns credentials are as follows\" \"Name\":\"John\", \"Jr\", \"Mobile\":\"945,234,1110\"";
Matcher m = p.matcher(str);
str = m.replaceAll("");
System.out.println(str);
}
Output
John loves cakes and he always orders them by dialing "989444 1234". Johns credentials are as follows" "Name":"John", "Jr", "Mobile":"9452341110"
This regex uses a positive lookbehind and a positive lookahead to only match commas with a preceding digit and a following digit, without including those digits in the match itself:
(?<=\d),(?=\d)
You could replace anything with the pattern (comma followed by a number) with the number itself.
x <- "I want to see 102,345,5 dogs, but not too soo; it's 3,242 minutes away"
gsub(",([[:digit:]])", "\\1", x)
#[1] "I want to see 1023455 dogs, but not too soo; it's 3242 minutes away"
#or
gsub(",([0-9])", "\\1", x)
#[1] "I want to see 1023455 dogs, but not too soo; it's 3242 minutes away"
Using Perl regexp, and focusing on "digit comma digit" we then replace with just the digits:
R> x <- "I want to see 102,345,5 dogs, but not too soo; it's 3,242 minutes away"
R> gsub("(\\d),(\\d)", "\\1\\2", x, perl=TRUE)
[1] "I want to see 1023455 dogs, but not too soo; it's 3242 minutes away"
R>
You may use any of the solutions below:
var s = "abc,def,2,100,xyz!,:))))";
Console.WriteLine(Regex.Replace(s, @"(\d),(\d)", "
2")); // Does not handle 1,2,3,4 cases
Console.WriteLine(Regex.Replace(s, @"(\d),(?=\d)", "$1")); // Handles consecutive matches with capturing group+backreference/lookahead
Console.WriteLine(Regex.Replace(s, @"(?<=\d),(?=\d)", "")); // Handles consecutive matches with lookbehind/lookahead, the most efficient way
Console.WriteLine(Regex.Replace(s, @",(?<=\d,)(?=\d)", "")); // Also handles all cases
See the C# demo.
Explanations:
(\d),(\d)- matches and captures single digits on both sides of,andare replacement backreferences that insert captured texts back into the result2
(\d),(?=\d)- matches and captures a digit before,, then a comma is matched and then a positive lookahead(?=\d)requires a digit after,, but since it is not consumed, onyl$1is required in the replacement pattern(?<=\d),(?=\d)- only such a comma is matched that is enclosed with digits without consuming the digits ((?<=\d)is a positive lookbehind that requires its pattern match immediately to the left of the current location),(?<=\d,)(?=\d)- matches a comma and only after matching it, the regex engine checks if there is a digit and a comma immediately before the location (that is after the comma), and if the check if true, the next char is checked for a digit. If it is a digit, a match is returned.
RegexHero.net test:

Bonus:
You may just match a pattern like yours with \d,\d and pass the match to the MatchEvaluator method where you may manipulate the match further:
Console.WriteLine(Regex.Replace(s, @"\d,\d", m => m.Value.Replace(",",string.Empty))); // Callback method
Here, m is the match object and m.Value holds the whole match value. With .Replace(",",string.Empty), you remove all commas from the match value.
You can always check a website that evaluates regex expressions. I think this code might be able to help you:
str = Regex.Replace(str, @",)(?<=(\d))", "");
You can simplify the regular expression:
num.replace(/,/g, '')
Replace the regex in the replace method with /,/g which means matches the character,literally (case sensitive)
var num = '12,312,313,214,214,324.89';
var num2 = '12,312,313,214,214,324';
function replaceComma(num) {
return num.replace(/,/g, '');
};
console.log(replaceComma(num));
console.log(replaceComma(num2));
Run code snippetEdit code snippet Hide Results Copy to answer Expand
- Find what:
\$(\d+),(\d+)(?:,(\d+))? - Replace with:
\1\2\3 - Search mode: Regular expression
Explanation:
\$matches the characther $\d+matches one or more digits. 1st capturing group,matches the comma\d+matches one or more digits. 2nd capturing group(?:,(\d+))?Non-capturing group that optionally matches the comma followed by one or more digits (3rd capturing group)
This will remove dollar and comma only within pair of parenthesis, as requested in question:
- Ctrl+H
- Find what:
(?:\(|\G\d+)\K$,) - Replace with:
LEAVE EMPTY - CHECK Match case
- CHECK Wrap around
- CHECK Regular expression
- UNCHECK
. matches newline - Replace all
Explanation:
(?: # non capture group
\( # opening parenthesis
| # OR
\G # restart from last match position
\d+ # 1 or more digits
) # end group
\K # reset operator, forget all we have seen until this position
[$,] # dollar sign or comma
(?= # positive lookahead, make sure we have after:
.*? # 0 or more any character, not greedy
\d # a digit
\) # closing parenthesis
) # end lookahead
Screenshot (before):

Screenshot (after):

Use a zero-width negative lookahead to make sure the to be replaced substrings (commas here) are not followed by {space(s)}{digit} at the end:
,(?!\s+\d$)
Example:
In [227]: text = '52A, XYZ Street, ABC District, 2'
In [228]: re.sub(',(?!\s+\d$)', '', text)
Out[228]: '52A XYZ Street ABC District, 2'
Edit:
If you have more commas after the ,{space(s)}{digit} substring, and want to keep them all, leverage a negative lookbehind to make sure the commas are not preceded by {space}{digit<or>[A-Z]}:
(?<!\s[\dA-Z]),(?!\s+\d,?)
Example:
In [229]: text = '52A, XYZ Street, ABC District, 2, M, Brown'
In [230]: re.sub('(?<!\s[\dA-Z]),(?!\s+\d,?)', '', text)
Out[230]: '52A XYZ Street ABC District, 2, M, Brown'
In [231]: text = '52A, XYZ Street, ABC District, 2'
In [232]: re.sub('(?<!\s[\dA-Z]),(?!\s+\d,?)', '', text)
Out[232]: '52A XYZ Street ABC District, 2'
If at the end is just a single digit you could use this. Can adapt if after the last comma are multiple digits(number 3 should be incremented).
text = '52A, XYZ Street, ABC District, 2'
text = text[:-3].replace(",", "") + text[-3:]
print(text)
The output is
52A XYZ Street ABC District, 2
Parsing CSV should be done with a proper csv parser. I would recommend perl as well.
perl -MText::ParseWords -ne '
@line = parse_line(",", 1, $_);
print join "," , map { s/,//g if $_ =~ /^[0-9,"]+$/; $_ } @line
' text.csv
Test:
$ cat text.csv
1,2,"12,345",x,y,"a,b"
"a,c","12,345",x,y,"a,b"
$ perl -MText::ParseWords -ne '
@line = parse_line(",", 1, $_);
print join "," , map { s/,//g if $_ =~ /^[0-9,"]+$/; $_ } @line
' text.csv
1,2,"12345",x,y,"a,b"
"a,c","12345",x,y,"a,b"
To make in-place changes you can use -i option or re-direct the output to another file.
Perl solution, using Text::CSV:
#!/usr/bin/perl
use warnings;
use strict;
use Text::CSV;
my @rows;
my $csv = 'Text::CSV'->new({ binary => 1}) or die 'Text::CVS'->error_diag;
open my $IN, '<', 'file.csv' or die $!;
while (my $row = $csv->getline($IN)) {
for my $cell (@$row) {
$cell =~ s/,// if $cell =~ /^[0-9,]+$/;
}
push @rows, $row;
}
$csv->eof or $csv->error_diag;
open my $OUT, '>', 'new.csv' or die $!;
$csv->print($OUT, $_) for @rows;
close $OUT or die $!;
You may use capturing groups to retain digits:
(\$\d+),(\d+)
and replace with $1$2. You may remove \$ if you do not care if it is a currency or not.
The (\$\d+),(\d+) regex matches:
(\$\d+)- Group 1 matching$as a literal symbol followed with 1 or more digits,- a literal comma(\d+)- Group 2 matching 1 or more digits
The $1 and $2 are backreferences that retrieve the texts stored in the memoru buffers for both groups.

/

Note that there are other ways to do the same, you can use lookarounds or a regex with \K, or using both, but capturing seems to me the most efficient solution for this case.
Ctrl + H, select "regular expression" (Alt + R) and replace:
\$\d+\K,(?=\d)
with nothing.
Explanation:
\$\d+\K will match dollar sign followed by one or more digit (we use the \K - the short form of the positive lookbehind to do a zero-width assertion). The next token "," matches a comma and finally we use a positive lookahead to match digits.
If I have the following code:
$Description = 'Value1, 20212707.1, Testing a description, today!' $Description = $Description -creplace '[,]*,', ''
Write-Host $Description
Line two uses Regex to find the first comma in the $Description variable. As I am not familiar with all regex, is there a function that could find the second comma and then replace it with my empty string? It would be nice to know if there is a way to actually find the second command and the space thereafter.
Curious if this is possible and for help!