#My struggle with Java, Regex and match groups

1 messages · Page 1 of 1 (latest)

keen vapor
#

Hey, working on a project, one of the parts allows users to add Meals and their ingredients.

What I have planned for the ingredient input is that users are allowed to enter input as follows:
"ingredientA, INGREDIENTB, iNGREDientC, ingredient D", respectively each ingredient should be split via comma and whitespace.

Regex I came up with:
"[a-zA-Z ]+([,][ ][a-zA-Z]+)*" (added screenshot from regex101)

However, I can not explain why matcher returns false in case of:
"oats, milk, banana, peanut butter"

Even though regex1 shows that all string is matched, even if " peanut" part is matched in a different group, shouldnt it still return true?

slow stoneBOT
#

<@&987246399047479336> please have a look, thanks.

karmic brook
#

might be an XY problem. Just split on ,\\s*

#

but you cant say [,][ ][a-zA-Z] like that

soft holly
#

and like Xorium said, you could just do .split(", ")

keen vapor
#

My idea was to do splitting after I validate the input, since it may also can come in as "rice, salmon, , avocado,, meat" or what not.

#

[a-z ]+(,\s+[a-z ]+)* this is the regex that ended up working as expected btw

keen vapor
#

thanks for your input guys, appreciated