2

I am trying to match the following two String objects with a regular expression. I am grouping and pulling out the values 3.00, 4.00, 100.00 from the first String; it works fine. However, I have a lot of String objects, and not all contain the third group, so I want to leave that group as optional. Thus I added a ? for that group to make it optional. Yet it doesn't make a difference, and any String without the third group portion is not matched by my regular expression.

How I can make the third group optional? And is there any advice as to whether or not my regular expression could be formatted better? Thank you!

Regular Expression

cost{"([0-9]+\.[0-9]+)[0-9"{]},+[a-zA-Z0-9]+{"+([0-9]+\.[0-9]+)[0-9A-Za-z"},{[\]\._-]+:price{"([0-9]+\.[0-9]+)?

String 1 which matches since it has third group values

cost{"3.00{},asdjdfhjkf23hawoutcome{"4.00"},79234gh3k2bdfsfgs2323g23jkg23{[]._-,bonus:price{"100.00"}jksdfjksdf222sdcfszfSDAWFD;

String 2 which doesn't match because it doesn't have third group values

cost{"5.00{},asdjdfhjkf23hawoutcome{"36.00"},79234gh3k2bdfsfgs2323g23jkg23{[]._-,jksdfjksdf222sdcfszfSDAWFD;
astrogeek14
  • 224
  • 1
  • 14
JasSy
  • 391
  • 3
  • 16

1 Answers1

0

You'll have to wrap all of group 3 in parentheses to make this work. I'm not sure exactly what you mean by it, but just going on what they contain, this is how your regex should look:

cost{"([0-9]+\.[0-9]+)[0-9"{]},+[a-zA-Z0-9]+{"+([0-9]+\.[0-9]+)[0-9A-Za-z"},{[\]\._-]+(:price{"([0-9]+\.[0-9]+))?

Notice the () around the last bit -- that's what makes the regex treat the whole thing as a single unit. Otherwise, it just looks at the last logical piece and sees the last (), not all of the part you want ignored.

Fund Monica's Lawsuit
  • 5,770
  • 8
  • 46
  • 65