tags:

views:

48

answers:

3

Hi, I have a String "REC/LESS FEES/CODE/AU013423".

What could be the regEx expression to match "REC" and "AU013423" (anything that is not surrounded by slashes /)

I am using /^>*/, which works and matches the string within slash's i.e. using this I am able to find "/LESS FEES/CODE/", but I want to negate this to find reverse i.e. REC and AU013423.

Need help on this. Thanks

+2  A: 

If you know that you're only looking for alphanumeric data you can use the regex ([A-Z0-9]+)/.*/([A-Z0-9]+) If this matches you will have the two groups which contain the first & final text strings.

This code prints RECAU013423

final String s = "REC/LESS FEES/CODE/AU013423";
final Pattern regex = Pattern.compile("([A-Z0-9]+)/.*/([A-Z0-9]+)", Pattern.CASE_INSENSITIVE);
final Matcher matcher = regex.matcher(s);
if (matcher.matches()) {
    System.out.println(matcher.group(1) + matcher.group(2));
}

You can tweak the regex groups as necessary to cover valid characters

Jon Freedman
A: 
^[^/]+|[^/]+$

matches anything that occurs before the first or after the last slash in the string (or the entire string if there is no slash present).

To iterate over all matches in a string in Java:

Pattern regex = Pattern.compile("^[^/]+|[^/]+$");
Matcher regexMatcher = regex.matcher(subjectString);
while (regexMatcher.find()) {
    // matched text: regexMatcher.group()
    // match start: regexMatcher.start()
    // match end: regexMatcher.end()
} 
Tim Pietzcker
+1  A: 

Here's another option:

String s = "REC/LESS FEES/CODE/AU013423";
String[] results = s.split("/.*/");
System.out.println(Arrays.toString(results));
// [REC, AU013423]
Alan Moore