1

I have written a regular expression to validate a name. The name can start with alphabetics and can be followed by alphabetics, numbers, a space or a _. The regex that I wrote is:

private static final String REGEX = "([a-zA-Z][a-zA-Z0-9 _]*)*"; 

If the input is: "kasklfhklasdhklghjsdkgsjkdbgjsbdjKg;" the program gets stuck on matcher.matches().

Pattern pattern = Pattern.compile(REGEX); Matcher matcher = pattern.matcher(input); if (matcher.matches()) { System.out.println("Pattern Matches"); } else { System.out.println("Match Declined"); } 

How can I optimize the regex?

3
  • To get the best performance ever, you should create your own String validator. Otherwise, let the JVM do the optimizations for you. Commented Dec 8, 2012 at 13:33
  • String validator? Is it a different strategy then REGEX validation? Commented Dec 8, 2012 at 13:36
  • It means parsing the String yourself and check any errors on it, more code but it can be faster than using Regex. Anyway, check the answers of people here. Commented Dec 8, 2012 at 13:37

1 Answer 1

4

Change your regex to:

private static final String REGEX = "[a-zA-Z][a-zA-Z0-9 _]*"; 

And it will match the String in a click.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.