Home > Blockchain >  Regex to check if a String starts with special characters like " " , "-" , "
Regex to check if a String starts with special characters like " " , "-" , "

Time:12-29

I have to write a Regex to check if a String starts with special characters like " " , "-" , "=" or "@" in Java.

To check for starting with " ", I've tried :

if (value.matches("^\\ .*$")) {
    System.out.println("Hey '" value);
}

I am being unable to use the 'or' in regex for the rest. I also don't want to check for each character since that would need compilation each time and that would be very slow.

Can anyone please help me out with an optimal regex.

Also would startsWith() be better and faster in this case?

CodePudding user response:

To check for the exact 4 special characters you mentioned in your question, use a character class in your regex pattern:

if (value.matches("[ =@-].*")) {
    System.out.println("Hey '"   value);
}
  • Related