0

My bean has a property called description. I need to write a regex to verify if there is any , in the string then it should be enclosed in double quotes.

@Pattern(regexp = "[,?""]*$") did not work for me.
1
  • If there is any what? Comma ,?
    – Robin
    Jun 12, 2014 at 14:40

2 Answers 2

1

The following will accept any description that does not contain a comma, regardless of whether it is surrounded by quotes. It also accepts any descriptions that contain a comma as long as they also are surrounded by quotes.

  • Valid: "A,B"
  • Valid: "A,B,C"
  • Valid: AB
  • Valid: "AB"
  • Invalid: A,B

If that's the case then the following should work:

@Pattern(regexp = "^([^,]*|\"[^,]*(,[^,]*)+\")*$")

Here's a breakdown of the significant parts of the regex:

  • ^ Matches start of line
  • [^,]* Matches zero or more non-commas
  • (,[^,]*)+ Matches at least one group of characters starting with a comma and followed by zero or more non-comma characters.
  • $ Matches end of line

The other ()* components just mean that this pattern can be repeated zero or more times.

7
  • Valid: "A,B" Invalid: A,B
    – mohanaki
    Jun 12, 2014 at 15:17
  • If a comma exists in the description then the whole description has to be surrounded by quotes. If no comma is present then the surrounding quotes are not required. Are these correct? Valid: AB Valid: "AB" Valid: "A,B" Invalid: A,B Jun 12, 2014 at 16:03
  • I've updated the pattern based on the new info and how I think you're suggesting the validation should work. Jun 12, 2014 at 16:44
  • The string itself is invalid as you are using double quotes in between.
    – mohanaki
    Jun 12, 2014 at 21:00
  • Easy enough to fix. The editor I use tries to be smart about copying text from inside strings by unescaping escaped printable-characters. Jun 13, 2014 at 12:05
0

You have double quotes inside your double code which will not be accepted as a valid Java String , try to set \ before the nested double quotes , the [] is an OR operator in regex which means one of the specified element iside the bracket . so i think for your requirement the pattern should be :

@Pattern(regexp = "((\",\")|.*)*$")
2
  • It did not work.My string may or may not contain a comma(,).If it is present it should be enclosed in double quote.
    – mohanaki
    Jun 12, 2014 at 14:55
  • @mohan141 even this ?
    – Mifmif
    Jun 12, 2014 at 14:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.