簡體   English   中英

特殊字符$的正則表達式

[英]Regular expression for special character $

我有一個字符串“ any tag $ @ ws2-role $ @ ws1-role”,我想有一個正則表達式來搜索以“ $ @”開頭,以“ $ @”或行尾結尾的單詞。

例如,對於上述輸入,輸出必須為ws2-role和ws1-role。

我在正則表達式下面嘗試過,但是我無法弄清楚如何為pattern2添加或運算符,以便它也可以考慮給出輸出的行尾,例如$ @ | $。 $ @是要匹配的確切單詞,而$則要查找到行尾為止。

String pattern1 = "$@";
String pattern2 = "$@";
Pattern pattern = Pattern.compile(Pattern.quote(pattern1) + "(.*?)" + Pattern.quote(pattern2));
    Matcher matcher = pattern.matcher(tag);
    // check all occurance
    while (matcher.find()) {
      System.out.println(matcher.group());
    }

任何人都可以給一些提示嗎?

提前謝謝了

嘗試這個

Pattern pattern = Pattern.compile("\\$@([^\\$@]+|$)");
CharSequence tag = "any tag$@ws2-role$@ws1-role";
Matcher matcher = pattern.matcher(tag);
while (matcher.find()) {
    System.out.println(matcher.group(1));
}

輸出量

ws2-role
ws1-role

您可以為此使用基於前瞻的正則表達式:

String regex = "\\$@\\S+(?=\\$@|$)";

暫無
暫無

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

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