Regex for string first chars - Model validation

Hello everyone, in my Rails app I need to validate a string that on creation can not have its first chars empty or composed by any special chars.

For example: " file" and “%file” aren’t valid. Do you know what Regex I should use?

Thanks!

Hello everyone, in my Rails app I need to validate a string that on creation can not have its first chars empty or composed by any special chars.

For example: " file" and “%file” aren’t valid. Do you know what Regex I should use?

You could utilize the “anchor” for this – that is you say that the line must “begin” with the characters that match the following regex.

Something like: /\A[\w]+$/ would work.

Note that \w will match an underscore. Don’t know if you consider that “special” or not…

Hello, thanks for the reply, but after applying this regex I go to rails console and run

a = File.new

a.file_name = " example.txt"

It still works, when it shouldn’t… any more help?

Underscore is allowed.

Philip's idea seems pretty good: ^\w+ That says: look for any string that starts with one or more "word" characters (letters, numbers, underscores). Try it out in rubular:

It let's you quickly experiment with lots of regular expressions and has a quick-ref right there on the page.