Reputation: 532
I am working in a regular expresion to match with the following string.
String sample1 = "key:value|key:value|key:value|key:value";
As you can see key:value is periodically repeating and the only separator is the pipe (|).
Considerations :
key => just letters value => letters, + - sings, and numbers (for the moment)
In the order hand , I have the following regex :
public void testOptionsRules()
{
String match = "[a-z]+[:][-+]?[a-z_0-9]+";
boolean option1 = "a:f".matches(match);
boolean option2 = "ad:d".matches(match);
boolean option3 = "addc:dd1".matches(match);
boolean option4 = "min:50".matches(match);
boolean option5 = "ssss:-10".matches(match);
boolean option6 = "dropl2etx:5555".matches(match);
assertTrue(option1 && option2 && option3 && option4 && option5);
assertFalse(option6);
}
The last test is working great. But How can I match the periodic repetition. I mean key:value|key:value|key:value|key:value.
Thanks
Upvotes: 2
Views: 1239
Reputation: 20163
You can use a matcher to cycle through each match in your string:
import java.util.regex.Pattern;
import java.util.regex.Matcher;
/**
<P>{@code java RegexForRepeatingString}</P>
**/
public class RegexForRepeatingString {
public static final void main(String[] ignored) {
String sRegex = "\\b[a-z]+:[+-]?[a-z_0-9]+\\b";
String sToSearch = "keya:valuea|keyb:valueb|keyc:valuec|keyd:valued";
Matcher m = Pattern.compile(sRegex).matcher(sToSearch);
while(m.find()) {
System.out.println(m.group());
}
}
}
Output:
[C:\java_code\]java RegexForRepeatingString
keya:valuea
keyb:valueb
keyc:valuec
keyd:valued
Upvotes: 4