how to match whitespace and alphanumeric characters in python

66,705
import re

test = "this matches"
match = re.match('(\w+\s\w+)', test)
print match.groups()

returns

('this matches',)
Share:
66,705
Paulo
Author by

Paulo

django CMS Core developer.

Updated on July 05, 2022

Comments

  • Paulo
    Paulo almost 2 years

    I'm trying to match a string that has a space in the middle and alphanumeric characters like so:

    test = django cms
    

    I have tried matching using the following pattern:

    patter = '\s'
    

    unfortunately that only matches whitespace, so when a match is found using the search method in the re object, it only returns the whitespace, but not the entire string, how can I change the pattern so that it returns the entire string when finding a match?

  • John Machin
    John Machin over 13 years
    (1) redundant parentheses (2) the OP is using search() not match()
  • BasedRebel
    BasedRebel over 13 years
    @John Machin: (1) to my way of thinking the parentheses emphasize that the entire group is returned; (2) it will work equally well with re.search().
  • Jake Anderson
    Jake Anderson about 4 years
    The above regex will work if there is exactly one space in the phrase but I'd suggest changing it to this to match any amount of whitespace-separated words: match = re.match("([\w|\s]+)", test)