dbmaven
dbmaven

Reputation: 11

regular expression replacement of numbers

Using regular expression how do I replace 1,186.55 with 1186.55?

My search string is

\b[1-9],[0-9][0-9][0-9].[0-9][0-9]

which works fine. I just can't seem to get the replacement part to work.

Upvotes: 0

Views: 160

Answers (4)

smac89
smac89

Reputation: 43078

Python:

def repl(initstr, unwanted=','):
    res = set(unwanted)
    return ''.join(r for r in initstr if r not in res)

Using regular expressions:

from re import compile
regex = compile(r'([\d\.])')
print ''.join(regex.findall('1,186.55'))

Using str.split() method:

num = '1,186.55'
print ''.join(num.split(','))

Using str.replace() method:

num = '1,186.55'
print num.replace(',', '')

Upvotes: 1

stema
stema

Reputation: 92976

You are very sparse with information in your question. I try to answer as general as possible:

You can shorten the regex a bit by using quantifiers, I would make this in a first step

\b[1-9],[0-9]{3}.[0-9]{2}

Most probably you can also replace [0-9] by \d, is also more readable IMO.

\b\d,\d{3}.\d{2}

Now we can go to the replacement part. Here you need to store the parts you want to keep. You can do that by putting that part into capturing groups, by placing brackets around, this would be your search pattern:

\b(\d),(\d{3}.\d{2})

So, now you can access the matched content of those capturing groups in the replacement string. The first opening bracket is the first group the second opening bracket is the second group, ...

Here there are now two possibilities, either you can get that content by \1 or by $1

Your replacement string would then be

\1\2

OR

$1$2

Upvotes: 2

SzG
SzG

Reputation: 12619

Or in Perl:

s/(\d+),(\d+)/$1$2/

Upvotes: 0

No Idea For Name
No Idea For Name

Reputation: 11577

if you just wanna remove the comma you can do(in java or C#):

str.Replace(",", "");

(in java it's replace)

Upvotes: 0

Related Questions