0

请向我推荐括号中带有 s 的单词的正则表达式

前任:hello(s)

我应该得到hello输出

请建议我

我试过这些

[a-z]\\(s\\)

[a-z]\\(\\s\\)
4

5 回答 5

4

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\\))
于 2013-08-21T12:38:40.280 回答
1

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));
于 2013-08-21T12:37:24.387 回答
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_ptrwould not be taken into account.

于 2013-08-21T12:37:35.733 回答
1

你也可以试试这个

 "hello(s)".replaceAll("\\(.*?\\)","")
于 2013-08-21T12:45:39.700 回答
0

你可以试试正则表达式:

(?<=\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?"
}
于 2013-08-21T13:49:08.640 回答