regex matching

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Patrick C
    New Member
    • Apr 2007
    • 54

    regex matching

    if i have a string, let's say its

    xx = 'abc123def456gh i"

    i'm having problems figuring out a way to know if xx[0] is a letter or number, then check xx[1] for the same thing and so on and so forth.

    what i thought would be easiest is doing somethign through regex
    have
    pattern1 = re.compile('[a-z]')
    pattern2 = re.compile('[0-9]')

    can i make a loop that check something like...
    Code:
    j = 0
    while j < len(xx):
        if j == pattern1:
            print "its a letter"
  • bvdet
    Recognized Expert Specialist
    • Oct 2006
    • 2851

    #2
    Originally posted by Patrick C
    if i have a string, let's say its

    xx = 'abc123def456gh i"

    i'm having problems figuring out a way to know if xx[0] is a letter or number, then check xx[1] for the same thing and so on and so forth.

    what i thought would be easiest is doing somethign through regex
    have
    pattern1 = re.compile('[a-z]')
    pattern2 = re.compile('[0-9]')

    can i make a loop that check something like...
    Code:
    j = 0
    while j < len(xx):
        if j == pattern1:
            print "its a letter"
    You can also do something like this:[code=Python]import string

    xx = 'abc123def456gh i>'

    for letter in xx:
    if letter in string.ascii_le tters:
    print '"%s" is a letter' % letter
    elif letter in string.digits:
    print '"%s" is a digit' % letter
    else:
    print '"%s" is neither a letter or a digit' % letter[/code]

    Comment

    • ghostdog74
      Recognized Expert Contributor
      • Apr 2006
      • 511

      #3
      Code:
      >>> map(str.isalpha,xx)
      [True, True, True, False, False, False, True, True, True, False, False, False, True, True, True]
      >>> zip(xx,map(str.isalpha,xx))
      [('a', True), ('b', True), ('c', True), ('1', False), ('2', False), ('3', False), ('d', True), ('e', True), ('f', True), ('4', False), ('5', False), ('6', False), ('g', True), ('h', True), ('i', True)]
      >>>

      Comment

      Working...