Regex - determine matrix from String
how can I create simple matrix for String that could be contains following combinations
123456 ABC
123456AB1
123456AB12
123456AB123
123456
for example
if ("\\d + \\d + \\d + \\d + \\d + \\d
+ \\s
+ [a-zA-Z]+[a-zA-Z]+[a-zA-Z]") {
//passed variant from input in form 123456 ABC
} else if ("\\d + \\d + \\d + \\d + \\d + \\d
+ [a-zA-Z]+[a-zA-Z]+[a-zA-Z]
+ \\d") {
//passed variant from input in form 123456AB1
} else if ("\\d + \\d + \\d + \\d + \\d + \\d
+ [a-zA-Z]+[a-zA-Z]+[a-zA-Z]
+ \\d + \\d") {
//passed variant from input in form 123456AB12
} else if ("\\d + \\d + \\d + \\d + \\d + \\d
+ [a-zA-Z]+[a-zA-Z]+[a-zA-Z]
+ \\d + \\d + \\d") {
//passed variant fro开发者_如何学编程m input in form 123456AB123
} else if ("\\d + \\d + \\d + \\d + \\d + \\d") {
//passed variant from input in form 0123456
} else {
//doesn't match
}
You could for instance use the following regexs
123456 ABC -> \\d{6}\\s\\w{3}
123456AB1 -> \\d{6}\\w{3}
123456AB12 -> \\d{6}\\w{4}
123456AB123 -> \\d{6}\\w{5}
123456 -> \\d{6}
The if-clauses can be used as in your example, e.g.,
if(str.matches("\\d{6}\\s\\w+") {
...
} ...
Just as your question, these regex variants only covers the exact combinations from this example.
If you need to split the input strings into the relevannt parts, try this regex: (\d{6})\s*([a-zA-Z]*)(\d*)
For 123456AB123
group 1 would be 123456
, group 2 would be AB
and group 3 would be 123
.
When groups are missing they'd just be an emtpy string.
Note that if the only difference between the variants would be the groups (group 1 always exists, groups 2 and 3 might be empty) then the if-else on different regexes would not be necessary. Instead you might have something like this (pseudocode):
if(matches) {
groups[3] = extractGroups();
//groups[0] should always exist
if(groups[1] is not empty) {
...
}
if(groups[2] is not empty) {
...
}
} else {
handle non-match
}
精彩评论