0

I've never been good at regular expressions. When ever I read about them, I sort of get a headache, get up from my desk, and forget what I'm doing. Attention difficulties.

But when I finally started making use of them in kwrite, I got a lot more comfortable with them. To the extent that, I can not now live without them.

Now, I need to sort of translate my knowledge of kwrite to python.

The kwrite regex [ ]+ matches a single space, two spaces, and a quadzillion spaces.

How do I match spaces like that in a python regular expression?

Also, the kwrite regex [0-9]+ matches 0, 10, 123, and 103984875749409202. How do I match those in a python regular expression?

1 Answer 1

2

You do it exactly the same way.

Python 2.7.2 (default, Oct 29 2011, 18:24:10) 
[GCC 4.5.3] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import re
>>> p = re.compile('[ ]+')
>>> print p.search('abc   def')
<_sre.SRE_Match object at 0x7f22ded9b100>
>>> print p.search('abc   def').group()
                              /// I promise there are three spaces there :)
>>> p = re.compile('[0-9]+')
>>> print p.search('abc123def').group()
123
>>> p = re.compile('[0-9cd]+')
>>> print p.search('abc123def').group()
c123d

The character class syntax ([abc]) is very common, and should be present in pretty much all regex implementations out there.

1
  • thanks. it's great to know that i can just go ahead and use the same style of regex. i can see kwrite being used in education to great effect.
    – ixtmixilix
    Jan 29, 2012 at 16:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .