NEO
NEO

Reputation: 2001

Using OR operator in a regular expression

How can I use OR in a Java regex? I tried the following, but it's returning null instead of the text.

Pattern reg = Pattern.compile("\\*+|#+ (.+?)");
Matcher matcher = reg.matcher("* kdkdk"); \\ "# aksdasd"
matcher.find();
System.out.println(matcher.group(1));

Upvotes: 0

Views: 136

Answers (1)

Ted Hopp
Ted Hopp

Reputation: 234857

The regex syntax for searching for X or Y is (X|Y). The parentheses are required if you have anything else in the pattern. You were searching for one of these patterns:

a literal * repeated one or more times

OR

a literal # repeated one or more times, followed by a space, followed by one or more of any character, matching a minimum number of times

This pattern matches * using the first part of the OR, but since that subpattern defines no capture groups, matcher.group(1) will be null. If you printed matcher.group(0), you would get * as the output.

If you want to capture the first character to the right of a space on a line that starts with either "*" or "#" repeated some number of times, followed by a space and at least one character, you probably want:

Pattern.compile("(?:\\*+|#+) (.+?)");

If you want everything to the right of the space, you want:

Pattern.compile("(?:\\*+|#+) (.+)");

Upvotes: 3

Related Questions