ankit f
ankit f

Reputation: 65

Regex with repeated rules

I want to write a regular expression with repeated rules.

String resList = "WW200020+ww200020";
if(resList!=null && (resList.matches("^([a-zA-Z]{2}[0-9%_]*)"))){ 
    resList =resList.substring(2);  
}

+ is the delimiter that can be optional. For example, it can also be like WW200020. I need to repeat the rule after the + symbol. How can I write a regular expression for repeated rules?

Please helpeme.

Upvotes: 0

Views: 446

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626738

You can obtain the expected output with 1 replaceAll and an updated regex (note the [+] in the square brackets so that we do not have to escape it, and ? quantifier making it optional, and also please note the final + quantifier that searches for the whole subpattern 1 or more times):

String resList = "WW200020+ww200020";
if(resList!=null && resList.matches("^([+]?[a-zA-Z]{2}[0-9%_]*)+")) { 
   resList =  resList.replaceAll("(?i)(?<=^|[+])[a-z]{2}([0-9%_]*)", "$1");
   System.out.println(resList); 
}

See IDEONE demo

The regex - (?i)(?<=^|[+])[a-z]{2}([0-9%_]*) - matches the following:

  • (?i) - Enforcing case-insensitive matching (the [a-z] will match [A-Z], too)
  • (?<=^|[+]) - The look-behind making sure there is start-of-string (^) or a plus symbol right before...
  • [a-z]{2} - 2 English letters
  • ([0-9%_]*) - 0 or more digits (0-9) or %, or _, captured into Group 1 that we reference in the replacement pattern as $1.

Upvotes: 1

Related Questions