Can anyone help me a bit with regexs? I currently have this: re.split(" +", line.rstrip())
, which separates by spaces.
How could I expand this to cover punctuation, too?
Join Stack Overflow to learn, share knowledge, and build your career.
Can anyone help me a bit with regexs? I currently have this: re.split(" +", line.rstrip())
, which separates by spaces.
How could I expand this to cover punctuation, too?
The official Python documentation has a good example for this one. It will split on all non-alphanumeric characters (whitespace and punctuation). Literally \W is the character class for all Non-Word characters. Note: the underscore "_" is considered a "word" character and will not be part of the split here.
re.split('\W+', 'Words, words, words.')
See https://docs.python.org/3/library/re.html for more examples, search page for "re.split"
'
and "
and *
, etc? This answer does that. As in My name's steve
will be split to My name
and s steve
.
– Steve P.
Nov 10 '13 at 20:24
import regex; L = regex.split(ur"\W+", u"किशोरी")
– jfs
Nov 10 '13 at 20:25
Using string.punctuation
and character class:
>>> from string import punctuation
>>> r = re.compile(r'[\s{}]+'.format(re.escape(punctuation)))
>>> r.split('dss!dfs^ #$% jjj^')
['dss', 'dfs', 'jjj', '']
import re
st='one two,three; four-five, six'
print re.split(r'\s+|[,;.-]\s*', st)
# ['one', 'two', 'three', 'four', 'five', 'six']
[][,;.-]
– tripleee
Sep 11 '15 at 5:00