简体   繁体   中英

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));

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("(?:\\*+|#+) (.+)");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM