1

I'm not that good with regular expressions...

I need a JavaScript regular expression that will do the following:

  1. The string can contain letters (upper and lower case), but not punctuations such as éàïç...
  2. The string can contain numbers (0..9) anywhere in the string, except on the first position.
  3. The string can contain underscores (_).

Valid strings:

  • foo
  • foo1
  • foo_bar
  • fooBar

Invalid strings:

  • 1foo --> number as first character
  • foo bar --> space
  • föo --> punctuation ö

Many thanks!

3
  • 1
    Are you looking for a CSS identifier validator? Although some validation rules are missing, this comes very close. Commented May 19, 2010 at 19:28
  • Nah it's for a naming system. These are my rules to "simplify" readability of those names. Commented May 19, 2010 at 19:32
  • Ah OK. Regardless, posted an answer :) Hope that helped. Commented May 19, 2010 at 19:36

1 Answer 1

9

This regex should do what you need:

/^[a-z_]+[\w]*$/i

Use it as follows:

var match = /^[a-z_]+[\w]*$/i.test(string);

Some explanation:

/      : start of JavaScript regex pattern
^      : start of string
[a-z_] : only alphabetic characters or underscore
+      : one or more
[\w]   : any word-character (aplhanumeric and the underscore)
*      : zero or more
$      : end of string
/      : end of JavaScript regex pattern
i      : case insensitive modifier

To learn more about regular expressions, you may find this site useful.

Sign up to request clarification or add additional context in comments.

2 Comments

Just needs an underscore in the [a-z]: [a-z_]
Yes, if the underscore may appear anywhere, then the [a-z] should indeed be [a-z_]. Hmm, actually, you're right he didn't explicitly forbid the underscore in the front. Updated answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.