user2663187
user2663187

Reputation: 39

regex for words in parenthesis in java

Please suggest me the regex for words which have s in parenthesis

ex: hello(s)

I should get hello as output

Please suggest me

I have tried these

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

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

Upvotes: 0

Views: 187

Answers (5)

Bernhard Barker
Bernhard Barker

Reputation: 55609

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

Upvotes: 1

Paul Vargas
Paul Vargas

Reputation: 42020

You can try the regular expression:

(?<=\p{L}+)\(s\)

\p{L} denote the category of Unicode letters. In ahother hand, you can to use a constant of java.util.regex.Pattern for avoid recompiled the expression every time, something like that:

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?"
}

Upvotes: 0

Ruchira Gayan Ranaweera
Ruchira Gayan Ranaweera

Reputation: 35557

You can try this too

 "hello(s)".replaceAll("\\(.*?\\)","")

Upvotes: 1

Joni
Joni

Reputation: 111249

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

Upvotes: 4

FrankPl
FrankPl

Reputation: 13315

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.

Upvotes: 1

Related Questions