javaregex

how to restrict more than 1 ampersand consecutively in java


I have a string that should contain one name then & and then second name. and two consecutive & should not occur. Also last character should not be &.

i have tried following code but this is not working

System.out.println("45345&&345".matches("(^(?!&)(?!.*&&)[0-9&]+(?<!&))$"));

regex is as (^(?!&)(?!.*&&)[0-9&]+(?<!&))$

but its not working!! Can you please help me.


Solution

  • Just one & on line and doesn't start or end with &:

    ^[^&]+&[^&]+$
    

    Can contain multiple &, but not consecutive ones and doesn't start or end with &:

    ^(?:[^&]+&)+[^&]+$