How can I use OR in a Java regex? I tried the following, but it's returning null
instead of the text.
如何在Java正则表达式中使用OR?我尝试了以下,但它返回null而不是文本。
Pattern reg = Pattern.compile("\\*+|#+ (.+?)");
Matcher matcher = reg.matcher("* kdkdk"); \\ "# aksdasd"
matcher.find();
System.out.println(matcher.group(1));
1 个解决方案
#1
3
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:
用于搜索X或Y的正则表达式语法是(X | Y)。如果模式中还有其他任何内容,则必须使用括号。您正在搜索以下模式之一:
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.
此模式使用OR的第一部分匹配*,但由于该子模式不定义捕获组,因此matcher.group(1)将为null。如果你打印matcher.group(0),你会得到*作为输出。
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("(?:\\*+|#+) (.+)");
#1
3
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:
用于搜索X或Y的正则表达式语法是(X | Y)。如果模式中还有其他任何内容,则必须使用括号。您正在搜索以下模式之一:
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.
此模式使用OR的第一部分匹配*,但由于该子模式不定义捕获组,因此matcher.group(1)将为null。如果你打印matcher.group(0),你会得到*作为输出。
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("(?:\\*+|#+) (.+)");