开发者

Regex for string first chars

开发者 https://www.devze.com 2023-02-10 04:40 出处:网络
in my Rails app I need to validate a string that on creation can not have its first chars开发者_StackOverflow empty or composed by any special chars.

in my Rails app I need to validate a string that on creation can not have its first chars开发者_StackOverflow empty or composed by any special chars.

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

Thanks!


The following regex will only match if the first letter of the string is a letter, number, or '_':

^\w

To restrict to just letters or numbers:

^[0-9a-zA-Z]

The ^ has a special meaning in regular expressions, when it is outside of a character class ([...]) it matches the start of the string (without actually matching any characters).

If you want to match all invalid strings you can place a ^ inside of the character class to negate it, so the previous expressions would be:

^[^\w]

or

^[^0-9a-zA-Z]


A good place to interactively try out Ruby regexes is Rubular. The link I gave shows the answer that @Dave G gave along with a few test examples (and at first glance it seems to work). You could expand the examples to convince yourself further.


The regex

^[^[:punct:][:space:]]+

Should do what you want. I'm not 100% sure of what Ruby provides as far as regular expressions and POSIX class support so your mileage on this may vary.

0

精彩评论

暂无评论...
验证码 换一张
取 消