簡體   English   中英

正則表達式用於Java括號中的單詞

[英]regex for words in parenthesis in java

請給我建議括號中帶有s的單詞的正則表達式

例如: hello(s)

我應該打個hello

請建議我

我嘗試過這些

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

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

為了不匹配字(s)它后面(即, 匹配hellohello(s)您可以用積極的前瞻

\\w+(?=\\(s\\))

它必須是一個或多個字母(以+表示):

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

要獲取不帶(s)的字符串,可以使用預讀或分組。

對於組,必需的字符串必須放在方括號中:

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

然后得到第一組,如下:

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

根據您假設是一個單詞,以下方法將起作用:

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

這只是假設小寫英文字母為單詞,如果您使用不區分大小寫的標志以及大寫字母。 但是不會考慮Jörgvar_ptr

你也可以嘗試

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM