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 ,? Commented 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.

Sign up to request clarification or add additional context in comments.

7 Comments

Valid: "A,B" Invalid: A,B
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
I've updated the pattern based on the new info and how I think you're suggesting the validation should work.
The string itself is invalid as you are using double quotes in between.
Easy enough to fix. The editor I use tries to be smart about copying text from inside strings by unescaping escaped printable-characters.
|
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 Comments

It did not work.My string may or may not contain a comma(,).If it is present it should be enclosed in double quote.
@mohan141 even this ?

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.