tags:

views:

107

answers:

3

I have to create a regular expression for some path conversion. Example for path are

//name:value /name:value // name:value
/name:value /name:value
/name:value//name:value

thing is how to check for // or / at the start or middle of the string and how can i specify that name can contain any of this a-zA-Z and _

Path also contains white spaces.

+4  A: 

This should help:

String s = "//name:value /name:value // name:value";
Pattern p = Pattern.compile("//?\\s*(\\w+):(\\w+)\\s*");
Matcher m = p.matcher(s);
while (m.find()) {
  System.out.printf("%s = '%s'%n", m.group(1), m.group(2));
}

Some notes:

  • It is assumed the / or // can delineate name:value pairs;
  • Optional white space after / or // and after name:value is ignored;
  • Both name and value are captured. You don't say what you want to capture. Adjust the parentheses as necessary;
  • Both name and value consist of A-Z, a-z, 0-9 or _ (that's what \w means).

If you don't want to find the values but simply test for the validity as a whole:

String s = "//name:value /name:value // name:value";
if (s.matches("(//?\\s*\\w+:\\w+\\s*)+")) {
  // it fits
}
cletus
+1  A: 

What exaclty do you want to archieve? Do you just want to check if an input is a valid path, or do you want to extract any matched groups for further conversion?

In any case a pattern that would match a string starting with / or // and a name and value consisting of a-zA-Z and _ would be:

(//?\s*[A-Za-z_]+:[A-Za-z_]+\s*)+
Philip Daubmeier
A: 

You can also use replaceAll to do the transformation if it's simple enough.

    String strings = "//cello:Yo-Yo Ma  / violin : Itzhak Perlman";
    System.out.println(strings.replaceAll(
        "//?\\s*(\\w+)\\s*:\\s*(.*?)\\s*(?=/|$)",
        "[$2] on [$1]\n"
    ));
    // "[Yo-Yo Ma] on [cello]"
    // "[Itzhak Perlman] on [violin]"
polygenelubricants