Jean
Jean

Reputation: 123

if then condition using regex in java

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.

Upvotes: 1

Views: 137

Answers (3)

Zissou
Zissou

Reputation: 227

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.

Upvotes: 0

Thorbear
Thorbear

Reputation: 2333

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.

Upvotes: 3

VladL
VladL

Reputation: 13033

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

\"string1\" :\"string2\"

Upvotes: 0

Related Questions