Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pattern matching with Java regex

Tags:

java

regex

My server dev gave me a regex that he says is the requirement for user name. It is @"^\w+([\s-]\w+)*$"

I need help figuring out right Java expression for this. It is confusing since I need to put some escape characters to make compiler happy.

I am trying this. Please let me know if this is right :

Pattern p = Pattern.compile("^\\w+([\\s-]\\w+)*\\$", Pattern.CASE_INSENSITIVE);

   Matcher m = p.matcher(username);

   if ((username.length() < 3 ) || (m.find())) {
      log ("Invalid pattern"); 
      return false;
   }

Is this correct ?

like image 321
techtinkerer Avatar asked Jul 27 '26 23:07

techtinkerer


1 Answers

The correct pattern is "^\\w+([\\s-]\\w+)*$".

$ denotes the end of the string, if you use \\$ it will force the string to have the char $ and that's not the intent.

like image 75
Wagner DosAnjos Avatar answered Jul 29 '26 13:07

Wagner DosAnjos



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!