import javax.validation.constraints.Pattern; public class A { @Pattern(regexp = "") private String values; // getter and setter } public class Main { public static void main(String[] args) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); A a = new A(); a.setValues("name1:value1,name2:value,name10:value7"); Set<ConstraintViolation<A>> constraintViolations = validator.validate(a); System.out.println(constraintViolations.size()); System.out.println(constraintViolations.iterator().next().getMessage()); } } 

Field private String values; contains comma separated values ​​(name: value, ..., ...). Where "name" and "value" should not be repeated. Separator ","

How to check in java language validity through one regex using @Pattern?:

  1. If Comma separated values ​​is valid - it contains the correct structure "name1: value1, name2: value, name10: value7"
  2. If the "name" does not repeat
  • What have you got? - 0xdb
  • | regex1 = ([^, (]) + ((? = :) | (. \)) - I select all "name" | | regex2 = ([^, (]) + ((? =,) | | (\ *)) - I select all "name: value" | | regex3 = \ b (\ w +) \ b \ s * (? =. * \ B \ 1 \ b) - I check if in the list "name1, name2, .. . "do not repeat" name "| **** How can I combine the result of regex1 with the following regular expression? **** - Andrei

2 answers 2

 ^((\w+):\w+(?!.*,\2:)(,|$))+$ 

For verification (in the browser, only Latin letters, numbers and underscores are suitable for \w , Java should do the right thing):

 input { outline: none; border: 1px solid; width: 100%; box-sizing: border-box; } :valid { border-color: green; } :invalid { border-color: red; } 
 <input pattern="^((\w+):\w+(?!.*,\2:)(,|$))+$" autofocus> 

  • Sorry, I was wrong. Your answer is good, but it doesn’t work for my script. Your regex does not work if both characters are set as a value (name1: abc345dddzzFgQ / 789Q ==) - Andrei
  • @Andrei, so replace \w with the set of required characters. For base64 it will be [A-Za-z0-9+/=] . In principle, you can more accurately verify the correctness of the value, if you think about it. - Qwertiy
  • Thank you for your good answer. He helped me. - Andrei
 import javax.validation.constraints.Pattern; public class A { @Pattern(regexp = "^(([A-Za-z0-9]+):[A-Za-z0-9+/=]+(?!.*,\2:)(,|$))*$") private String values; // getter and setter } public class Main { public static void main(String[] args) { ValidatorFactory factory = Validation.buildDefaultValidatorFactory(); Validator validator = factory.getValidator(); A a = new A(); a.setValues("name1:value1,name2:value,name10:value7"); Set<ConstraintViolation<A>> constraintViolations = validator.validate(a); System.out.println(constraintViolations.size()); System.out.println(constraintViolations.iterator().next().getMessage()); } }