1

I have a pattern which goes like this

String1 :"String2",

i have to validate this pattern. here if u see there are two cases, the somestring1 can contain special characters if it is given within double quotes.

eg: "xxxx-xxx" :"yyyyyyyy",--------> is valid
but  xxxx-xxx  :"yyyyyyyy",--------> is not valid
    "xxxx-xxx  :"yyyyyyyy",--------> is not valid

So i need to create a regex which will check whether the double quotes is closed properly if it is present in String1.

1
  • Why not just count the number of "s? Commented May 9, 2013 at 9:29

3 Answers 3

3

Short answer: Regex doesn't work like that.

What you can do however, is to use two separate patterns to validate:

\"[^\"]+?\" :.*

To check the one that can contain special characters, and:

[a-zA-Z]+? :.*

To check the one that can't

EDIT:

Thinking some more about it, you could combine the two patterns above like so:

^(\"[^\"]+?\"|[a-zA-Z]+?) :.*$

Which will match something :"something" and "some-thing" :"something" but not "some-thing : "something" or some-thing : "something". Assuming that the string only contains the given text.

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

Comments

0

If I understand your question right, this simple regex should work

\"string1\" :\"string2\"

Comments

0

Maybe something like this?

(?<normalString>^[a-zA-Z]+$)|(?<specialString>^".*?"$)

This will capture only a-z characters and put them in the "normalString" group, or if there's an string within quotation marks, capture that and put it in the "specialString" group.

1 Comment

I don't think Java support named capture groups though.

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.