20

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?

ROMANIA_engineer
  • 54,432
  • 29
  • 203
  • 199
Paulo
  • 6,982
  • 7
  • 42
  • 56
  • What do you consider an "alphanumeric character?" If letters, numbers and underscores, you'll find \w convenient. – jpsimons Feb 19 '11 at 01:36

2 Answers2

44
import re

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

returns

('this matches',)
Hugh Bothwell
  • 55,315
  • 8
  • 84
  • 99
  • (1) redundant parentheses (2) the OP is using `search()` not `match()` – John Machin Feb 19 '11 at 02:14
  • 4
    @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(). – Hugh Bothwell Feb 19 '11 at 03:58
  • 1
    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)` – Jake Anderson Apr 30 '20 at 14:40
2

In case there is more than one space use the following regexp:

'([\w\s]+)'

example

In [3]: import re

In [4]: test = "this matches and this"
   ...: match = re.match('([\w\s]+)', test)
   ...: print match.groups()
   ...: 
('this matches and this',)
Danil
  • 4,781
  • 1
  • 35
  • 50