a simple one for the Regex-perts =)

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • K. Shier

    a simple one for the Regex-perts =)

    my regex for matching phone #'s:
    \({0,1}(?<areac ode>[0-9]{3})\){0,1}( |-){0,1}(?<prefix >[0-9]{3})(
    |-){0,1}(?<suffix >[0-9]{4})

    which i then .Replace to become:
    (${areacode}) ${prefix}-${suffix}

    question: how do i fix the match regex so that it 'stops' after the suffix
    of the phone # is matched? right now, it will return '(800) 555-1212345' if
    i type in '8005551212345' - i just want '(800) 555-1212'.

    as always, any help would be much appreciated! thanks!


  • Jeremy Cowles

    #2
    Re: a simple one for the Regex-perts =)

    > my regex for matching phone #'s:[color=blue]
    > \({0,1}(?<areac ode>[0-9]{3})\){0,1}( |-){0,1}(?<prefix >[0-9]{3})(
    > |-){0,1}(?<suffix >[0-9]{4})[/color]

    I am no RegEx[pert] :-) but I think you have to join your groups as one.
    What is happening is that your <suffix> group is being repeated because
    [0-9]{4} can be found twice in 12121234, see: [1212] and [1234]. If you can
    join the entire expression as a single group, I think that /may/ fix your
    problem.

    HTH

    ~
    Jeremy

    Comment

    • Brian Davis

      #3
      Re: a simple one for the Regex-perts =)

      Regex.Replace simply replaces the matched text with the replacement string.
      The expression only matches '8005551212', so it replaces that with '(800)
      555-1212'. The '345' does not participate in the match, so it is left
      alone. If you want it to go away, you need to make it part of the match and
      then just leave it out of the replacement. Simply add '.*' to the end of
      your regex to match whatever is left over after the number is matched:

      \({0,1}(?<areac ode>[0-9]{3})\){0,1}( |-){0,1}(?<prefix >[0-9]{3})(
      |-){0,1}(?<suffix >[0-9]{4}).*


      Brian Davis




      "K. Shier" <ks4hire@spamAt YourOwnRisk.yah oo.com> wrote in message
      news:%23J7P109a DHA.2436@TK2MSF TNGP12.phx.gbl. ..[color=blue]
      > my regex for matching phone #'s:
      > \({0,1}(?<areac ode>[0-9]{3})\){0,1}( |-){0,1}(?<prefix >[0-9]{3})(
      > |-){0,1}(?<suffix >[0-9]{4})
      >
      > which i then .Replace to become:
      > (${areacode}) ${prefix}-${suffix}
      >
      > question: how do i fix the match regex so that it 'stops' after the[/color]
      suffix[color=blue]
      > of the phone # is matched? right now, it will return '(800) 555-1212345'[/color]
      if[color=blue]
      > i type in '8005551212345' - i just want '(800) 555-1212'.
      >
      > as always, any help would be much appreciated! thanks!
      >
      >[/color]


      Comment

      Working...