-1

I'm writing a simple validation for a filename with a rule that It should not contains any spaces and special symbols except underscore.

for space I will use the re.search :

          word = 'some thing'
          space_checker = bool(re.search(r"\s", word))

And for finding the speical characters except underscore all I know is the regex pattern :

           words_with_underscore = ^a-zA-Z0-9_

How to combine both of it to make the restriction ?

Wiktor Stribiżew
  • 484,719
  • 26
  • 302
  • 397
noobster
  • 612
  • 1
  • 5
  • 13
  • 1
    Try `re.search(r'\W', a)` https://stackoverflow.com/questions/22937618/reference-what-does-this-regex-mean – Nick May 08 '20 at 09:01

3 Answers3

0

For starters, this: words_with_underscore = ^a-zA-Z0-9_ is wrong. The correct regexp to match strings containing only letters, digits and underscore is: r'^[a-zA-Z0-9_]*$'

You could shorten it to r'^\w*$' since \w means "word character" (ie. letter, digit or underscore):

word = 'some thing'
good = bool(re.search(r"^\w*$", word))

And then, there is nothing to combine - this regexp does not match spaces, so it will fail for 'some thing and pass for 'some_thing'.

Błotosmętek
  • 11,945
  • 16
  • 26
0

Please try this:

^[a-zA-Z0-9_]*$
mtdot
  • 159
  • 8
0

You can do something like this

^[a-zA-Z0-9_]*$

  • FYI `[A-z]` matches more than just letters. Have a look at an [ASCII table](http://www.asciitable.com/). `?` and `!` are already included in `\W` so `[^?!\W]` is **strictly** equivalent to `[^\W]` that is also equivalent to `\w`, `\S` includes `[A-za-z0-9_]` so `[A-za-z0-9_\S]` <=> `\S`, your regex is equal to `\w\S\w+` and doesn't answer the question. – Toto May 08 '20 at 11:45
  • Thanks for correcting. – Nadeem Hilal May 08 '20 at 13:53