2

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

5
  • What do you expect sample1.matches(match) to return? Commented Mar 9, 2014 at 1:04
  • Are you trying to extract the "key:value"'s out of the String? Commented Mar 9, 2014 at 1:04
  • 2
    Why not just use split? Commented Mar 9, 2014 at 1:12
  • 1
    The minus needs to precede the plus: [-+]. Commented Mar 9, 2014 at 1:15
  • @EJP: Why does it have to be minus-plus if it's inside a character class? Commented Mar 9, 2014 at 4:18

1 Answer 1

4

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
Sign up to request clarification or add additional context in comments.

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.