请向我推荐括号中带有 s 的单词的正则表达式
前任:hello(s)
我应该得到hello
输出
请建议我
我试过这些
[a-z]\\(s\\)
[a-z]\\(\\s\\)
To match the word without the (s)
that follows it (that is, to match only hello
in hello(s)
) you can use positive lookahead:
\\w+(?=\\(s\\))
It needs to be one or more letters (denoted with a +
):
[a-z]+\\(s\\)
To get the string without the (s)
, you can either use look-ahead or groups.
For groups, the required string must be in brackets:
([a-z]+)\\(s\\)
And then get the first group, as follows:
String str = "hello(s)";
String regex = "([a-z]+)\\(s\\)";
Pattern p = Pattern.compile(regex);
Matcher m = p.matcher(str);
if (m.matches())
System.out.println(m.group(1));
Depending on what you assume to be a word, the following would work:
[a-z]+\\(s\\)
This just assumes lowercase English letters as words, and if you usse the case-insensitive flag as well uppercase letters. But Jörg
or var_ptr
would not be taken into account.
你也可以试试这个
"hello(s)".replaceAll("\\(.*?\\)","")
你可以试试正则表达式:
(?<=\p{L}+)\(s\)
\p{L}
表示 Unicode 字母的类别。另一方面,您可以使用常量java.util.regex.Pattern
来避免每次都重新编译表达式,如下所示:
private static final Pattern REGEX_PATTERN =
Pattern.compile("(?<=\\p{L}+)\\(s\\)");
public static void main(String[] args) {
String input = "hello(s), how are you?";
System.out.println(
REGEX_PATTERN.matcher(input).replaceAll("")
); // prints "hello, how are you?"
}