Priyank Thakkar
Priyank Thakkar

Reputation: 4852

RegEx performence issue

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?

Upvotes: 1

Views: 78

Answers (1)

Amir Pashazadeh
Amir Pashazadeh

Reputation: 7282

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.

Upvotes: 4

Related Questions