0

Anyone knows how to use regular expression to replace ",/d" with just the number "/d"? I tried using /d and it wouldn't work...it would replace the , followed by whatever number with the alphabet character "d".

Thanks in advance.

Aero Wang
  • 8,382
  • 14
  • 63
  • 99
  • 2
    Notice that you're using the wrong kind of slash. All the escape sequences in regex (and most other constructs) use backslash, not forward slash. – Barmar Dec 02 '12 at 05:21

2 Answers2

5

You capture what you want to keep and use it in the replacement:

s/,(\d)/$1/;
ysth
  • 96,171
  • 6
  • 121
  • 214
5

Just remove any comma that precedes a number, using a look-ahead:

s/,(?=\d)//

If you tried s/,\d/\d/, Perl would view the replacement as a double quoted string. As there is no escape code \d, the backslash is simply ignored, and d used.

If you want to substitute the match with a part of the match, you have to use captures (see ysth's answer).

My above substitution doesn't include the digit in the matched string, therefore just substituting the comma with the empty string (i.e. deleting it), but still asserts that the comma is followed by a digit.

amon
  • 57,091
  • 2
  • 89
  • 149
  • 1
    This is faster than ysth's version. – ikegami Dec 02 '12 at 09:13
  • 1
    @ikegami: data dependent. if only 1% of commas are followed by digits, mine is faster. that is unlikely, though :) – ysth Dec 02 '12 at 10:54
  • @ysth, Good point, I never thought of it that way for code like this. – ikegami Dec 02 '12 at 11:03
  • 1
    @ysth: I'm interested in the reason for this being sometimes-faster-sometimes-not. Asked a [new question](http://stackoverflow.com/questions/13682758/why-is-lookahead-sometimes-faster-than-capturing) and would appreciate clarification. – mpe Dec 03 '12 at 12:11
  • @mpe: my assumption would be the match (or rather fail to match) is slightly faster in mine but the substitution is much faster in amom's – ysth Dec 03 '12 at 15:15