String check for a large number of different incremental values

I am currently checking the line for the following:

if(parseCommand.contains("vlan1") || parseCommand.contains("Fa0/1i") || parseCommand.contains("Fa0/1o") || parseCommand.contains("Fa1/0") || parseCommand.contains("Fa1/1") || parseCommand.contains("Fa1/2") || parseCommand.contains("Fa1/3") || parseCommand.contains("Fa1/4") || parseCommand.contains("Fa1/5") || parseCommand.contains("Fa1/6") || parseCommand.contains("Fa1/7") || parseCommand.contains("Fa1/8") || parseCommand.contains("Fa1/9") || parseCommand.contains("Fa1/11") || parseCommand.contains("Gi0")) { //do things here } 

However, it may contain vlan1 before vlan4094, and I have to check them out. What is the easiest way to do this, I have to stick with all of this in a for loop increasing to 4094, I think?

  for (int i = 1; i <= 4094; i++) { if(parseCommand.contains("vlan"[i])) { //do stuff here } } if(other conditions from above) { //do same stuff again here } 

Or else, I could stick to all the conditions in the for loop and do everything inside. It all seems messy, is there a useless way to do this?

+4
source share
3 answers

I think this regex should do this:

 String parseCommand = "vlan4094"; if (parseCommand.matches(".*?vlan([1-3][0-9]{3}|" + "[1-9][0-9]{0,2}|" + "40(9[0-4]|[0-8][0-9])).*")) System.out.println("matches"); 

[1-3][0-9]{3} - 1000-3999
[1-9][0-9]{0,2} - 1-999
9[0-4] - 90-94
[0-8][0-9] - 00-89
40(9[0-4]|[0-8][0-9]) - 4000-4094

Something like this is probably simpler:

 String parseCommand = "vlan4094"; if (parseCommand.startsWith("vlan")) { int v = Integer.parseInt(parseCommand.substring(4)); if (v >= 1 && v <= 4094) /* do stuff */ } 

Proposed Change:

Replace:

 parseCommand.contains("Fa1/0") || parseCommand.contains("Fa1/1") || parseCommand.contains("Fa1/2") || parseCommand.contains("Fa1/3") || parseCommand.contains("Fa1/4") || parseCommand.contains("Fa1/5") || parseCommand.contains("Fa1/6") || parseCommand.contains("Fa1/7") || parseCommand.contains("Fa1/8") || parseCommand.contains("Fa1/9") 

with

 parseCommand.matches(".*?Fa1/[0-9].*") 
+6
source

If the only problem is with "vlanXXX", you can remove part of the "vlan" line:

 parseCommand = parseCommand.replaceFirst("vlan", ""); 

and then translate it to int

 int value = Integer.parseInt(parseCommand); 

and then comparing this result with what you want

 if((value >= 1) && (value <= 4094)){....} 

This will only work for this case, and you will have to handle the case where parseCommand cannot be passed to int. And this is much more understandable than using any regular expression

+1
source

You can combine them into one logical

 boolean b = false; for(int i = 1 ; i < 4094 ; i ++){ b = b || parseCommand.contains("vlan" + i); } 

Then check your boolean

0
source

All Articles