rodrigoalvesvieira
rodrigoalvesvieira

Reputation: 8062

Regex for string first chars

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!

Upvotes: 0

Views: 3469

Answers (3)

JeffH
JeffH

Reputation: 10482

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.

Upvotes: 1

Andrew Clark
Andrew Clark

Reputation: 208495

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]

Upvotes: 3

Dave G
Dave G

Reputation: 9777

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.

Upvotes: 0

Related Questions