Question

I'm working with Python bindings for Qt4.8 on OS X.

  • I want to accept any digit and a few other chars AND white space.
  • String can be empty or at any length.
  • What I don't want is, for the string to being or end with white space.

My working example: '[0-9pqw\+\-\*\#\(\)\.][0-9pqw\+\-\*\# \(\)\.]*'

However, I don't want to repeat two blocks one containing space one does not. There should be a better way I guess, employing [^ ], but how?

Second question:

  • If I want to limit strings total length, how would I do it?

Thank you.

Was it helpful?

Solution

You could use negative lookarounds at the beginning and end of the pattern:

^(?![ ])[0-9pqw+*# ().-]*(?<![ ])$

Note that the brackets are not necessary but aid readability. Neither are any of your escapes (as long as you put the - at the end).

OTHER TIPS

Does this not do what you want?

import re 
re.match('^[^\W].*[^\W]$', '  aaa ')

(Where the last arg is your test string).

If you want to ensure the length is less than a certain amount use curly braces. One character is already spent testing the first and last chars of the test string with the inclusion of the [^\W] notation. So in this example, there is a match when there are no spaces at either side and when the test string is no longer than 4 characters.

re.match('^[^\W].{1,2}[^\W]$', 'aaaa')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top