2

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 from input in form 123456AB123

} else if ("\\d + \\d + \\d + \\d + \\d + \\d") {
   //passed variant from input in form 0123456

} else {
   //doesn't match
}
2
  • 1
    Can you give examples of what shouldn't match? Commented Sep 6, 2011 at 10:56
  • down-votes are welcome, maybe I first person who don't understand for example this thread stackoverflow.com/questions/7318469/…, :-) Commented Sep 6, 2011 at 11:04

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.