Reputation: 6543
I am trying to validate a string in a 'iterative way' and all my tryouts just fail! I find it a bit complicated and i'm guessing maybe you could teach me how to do it right. I assume that most of you will suggest me to use regex patterns but i dont really know how, and in general, how can a regex be defined for infinite "sets"?
The string i want to validate is "ANYTHING|NUMBER_ONLY,ANYTHING|NUMBER_ONLY..."
for example: "hello|5,word|10" and "hello|5,word|10," are both valid.
note: I dont mind if the string ends with or without a comma ','.
Upvotes: 0
Views: 271
Reputation: 8014
Kleene star (*
) lets you define "infinite sets" in regular expressions. Following pattern should do the trick:
[^,|]+\|\d+(,[^,|]+\|\d+)*,?
A----------B--------------C-
Part A matches the first element. Part B matches any following elements (notice the star). Part C is the optional comma at the end.
WARNING: Remember to escape backslashes in Java string.
Upvotes: 1
Reputation: 15434
I'd suggest splitting your string to array by |
delimiter. And validate each part separately. Each part (except first one) should match following pattern \d+(,.*)?
UPDATED
Split by ,
and validate each part with .*|\d+
Upvotes: 1