w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Java Regex match anything that matches given pattern and is not between a given character

Here is a single-pattern implementation of your solution:

String input = "part1+250+|part2|+part3";

Pattern p = 
//                   | group 1 ("variable")
//                   | | positive look behind for "|"
//                   | |      | character class for allowed characters
//                   | |      |             | quantifier for 1+ instance,
greedy
//                   | |      |             | | positive lookahead for "|"
//                   | |      |             | |      | OR
//                   | |      |             | |      || group 2
("constant") 
//                   | |      |             | |      ||| negative
lookbehind for "|"
//                   | |      |             | |      |||       | allowed
chars
//                   | |      |             | |      |||       |           
 | quantifier
//                   | |      |             | |      |||       |           
 | | negative
//                   | |      |             | |      |||       |           
 | | lookahead
//                   | |      |             | |      |||       |           
 | | 
    Pattern.compile("((?<=\|)[ a-zA-Z0-9_-]+(?=\|))|((?<!\|)[
a-zA-Z0-9_-]+(?!\|))");
Matcher m = p.matcher(input);
while (m.find()) {
    System.out.printf("Variable: %s%nConstant: %s%n", m.group(1),
m.group(2));
}

Output

Variable: null
Constant: part1
Variable: null
Constant: 250
Variable: part2
Constant: null
Variable: null
Constant: part3

Notes

  • Here it prints everything, but you can of course check for nulls and infer whether a "variable", a "constant", or nothing's been found.
  • Quick solution here, so there might be edge cases not covered.
  • Grouping here is Java 6 styled for backwards compatibility. Java 7's named groups are a lot more fun though!




© Copyright 2018 w3hello.com Publishing Limited. All rights reserved.