Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to match whitespace and alphanumeric characters in python

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?

like image 814
Paulo Avatar asked Feb 19 '11 00:02

Paulo


People also ask

Is alphanumeric with space Python?

Python String isalnum() Method The isalnum() method returns True if all the characters are alphanumeric, meaning alphabet letter (a-z) and numbers (0-9). Example of characters that are not alphanumeric: (space)!

How do you match a space in Python?

\s | Matches whitespace characters, which include the \t , \n , \r , and space characters. \S | Matches non-whitespace characters. \b | Matches the boundary (or empty string) at the start and end of a word, that is, between \w and \W .

How do you match a character in Python?

Using m option allows it to match newline as well. Matches any single character in brackets. Matches 0 or more occurrences of preceding expression. Matches 1 or more occurrence of preceding expression.

How do you match a string with spaces in Python?

Python String isspace() Method. Python String isspace() method returns “True” if all characters in the string are whitespace characters, Otherwise, It returns “False”. This function is used to check if the argument contains all whitespace characters, such as: ' ' – Space.


2 Answers

import re

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

returns

('this matches',)
like image 163
Hugh Bothwell Avatar answered Oct 06 '22 19:10

Hugh Bothwell


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',)
like image 39
Daniil Mashkin Avatar answered Oct 06 '22 18:10

Daniil Mashkin