[英]Java: validating a certain string pattern
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..." 我要验证的字符串是“ANYTHING | NUMBER_ONLY,ANYTHING | NUMBER_ONLY ......”
for example: "hello|5,word|10" and "hello|5,word|10," are both valid. 例如:“hello | 5,word | 10”和“hello | 5,word | 10”都有效。
note: I dont mind if the string ends with or without a comma ','. 注意:我不介意字符串是否以逗号','结尾。
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+(,.*)?
每个部分(第一个除外)应匹配以下模式
\\d+(,.*)?
UPDATED 更新
Split by ,
and validate each part with .*|\\d+
斯普利特
,
并验证每一部分.*|\\d+
Kleene star ( *
) lets you define "infinite sets" in regular expressions. Kleene star (
*
)允许您在正则表达式中定义“无限集”。 Following pattern should do the trick: 以下模式应该做的伎俩:
[^,|]+\|\d+(,[^,|]+\|\d+)*,?
A----------B--------------C-
Part A matches the first element. A部分匹配第一个元素。 Part B matches any following elements (notice the star).
B部分匹配以下任何元素(注意星形)。 Part C is the optional comma at the end.
C部分是最后的可选逗号。
WARNING: Remember to escape backslashes in Java string. 警告:请记住在Java字符串中转义反斜杠。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.