Trouble with regex

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Fernando Rodriguez

    Trouble with regex

    Hi,

    I'm trying to write a regex that finds whatever is between ${ and } in a text
    file.

    I tried the following, but it only finds the first occurrence of the pattern:
    [color=blue][color=green][color=darkred]
    >>> s = """asssdf${ 123}[/color][/color][/color]
    dgww${one} ${two}"""[color=blue][color=green][color=darkred]
    >>> what = re.compile("\$\ {([^}]*)\}")
    >>> m = what.search(s)
    >>> m.groups()[/color][/color][/color]
    ('123',)

    What am I doing wrong? O:-)
  • anton muhin

    #2
    Re: Trouble with regex

    Fernando Rodriguez wrote:[color=blue]
    > Hi,
    >
    > I'm trying to write a regex that finds whatever is between ${ and } in a text
    > file.
    >
    > I tried the following, but it only finds the first occurrence of the pattern:
    >
    >[color=green][color=darkred]
    >>>>s = """asssdf${ 123}[/color][/color]
    >
    > dgww${one} ${two}"""
    >[color=green][color=darkred]
    >>>>what = re.compile("\$\ {([^}]*)\}")
    >>>>m = what.search(s)
    >>>>m.groups( )[/color][/color]
    >
    > ('123',)
    >
    > What am I doing wrong? O:-)[/color]

    Nothing ;) search just finds first match. If you want to find all
    non-overlapping matches try finditer:

    import re

    s = """asssdf${ 123}

    dgww${one} ${two}"""

    what = re.compile("\$\ {([^}]*)\}")
    for m in what.finditer(s ):
    print m.groups()

    prints:
    ('123',)
    ('one',)
    ('two',)

    regards,
    anton.

    Comment

    • Jim Shapiro

      #3
      Re: Trouble with regex


      "Fernando Rodriguez" <frr@easyjob.ne t> wrote in message
      news:52p9rvs6av 0dqe59t733o5net cd9t6r7q2@4ax.c om...[color=blue]
      > Hi,
      >
      > I'm trying to write a regex that finds whatever is between ${ and } in a[/color]
      text[color=blue]
      > file.
      >
      > I tried the following, but it only finds the first occurrence of the[/color]
      pattern:[color=blue]
      >[color=green][color=darkred]
      > >>> s = """asssdf${ 123}[/color][/color]
      > dgww${one} ${two}"""[color=green][color=darkred]
      > >>> what = re.compile("\$\ {([^}]*)\}")
      > >>> m = what.search(s)
      > >>> m.groups()[/color][/color]
      > ('123',)
      >
      > What am I doing wrong? O:-)[/color]

      Try:

      import re

      s = """asssdf${ 123}
      dgww${one} ${two}"""
      what = re.compile("\$\ {([^}]*)\}") # same as original
      m = what.findall(s)
      print m
      [color=blue]
      >regex_test.p y[/color]
      ['123', 'one', 'two']

      HTH

      Jim Shapiro


      Comment

      Working...