簡體   English   中英

正則表達式匹配最多一個字符(如果出現)

[英]Regex matching up to a character if it occurs

我需要匹配如下字符串:

  1. 匹配所有內容;
  2. 如果-出現,只匹配-不包括-

例如:

  • abc; 應該返回abc
  • abc-xyz; 應該返回abc

Pattern.compile("^(?<string>.*?);$");

使用上面我可以達到一半。 但不知道如何改變這種模式來實現第二個要求。 我如何更改.*? 以便它在出現以下情況時停止-

我不擅長正則表達式。 任何幫助都會很棒。

編輯

我需要將其捕獲為組。 我無法更改它,因為還有許多其他模式需要匹配和捕獲。 它只是我發布的一部分。

代碼如下所示。

public static final Pattern findString = Pattern.compile("^(?<string>.*?);$");
if(findString.find())
    {
        return findString.group("string"); //cant change anything here.

    }

只需使用否定的字符類。

^[^-;]*

IE。

Pattern p = Pattern.compile("^[^-;]*");
Matcher m = p.matcher(str);
while(m.find()) {
System.out.println(m.group());
}

這將匹配開頭的任何字符,但不匹配-; ,零次或多次。

這應該做你正在尋找的:

[^-;]*

它匹配不是-;字符; .

Tipp:如果您對正則表達式不確定,有很棒的在線解決方案來測試您的輸入,例如https://regex101.com/

更新

我看到您在代碼中遇到了問題,因為您嘗試訪問Pattern對象中的.group ,而您需要使用Matcher對象的.group方法:

public static String GetTheGroup(String str) {
    Pattern findString = Pattern.compile("(?s)^(?<string>.*?)[;-]");
    Matcher matcher = findString.matcher(str);
    if (matcher.find())
    {
        return matcher.group("string"); //you have to change something here.
    }
    else
        return "";
}

並將其稱為

System.out.println(GetTheGroup("abc-xyz;"));

IDEONE 演示

舊答案

您的^(?<string>.*?);$正則表達式僅匹配 0 個或多個字符,而不是從開頭到第一個的換行符; 那是字符串中的最后一個字符。 我想這不是你所期望的。

您應該了解有關在正則表達式中使用字符類的更多信息,因為您可以匹配使用[...]定義的指定字符集中的1 個符號。

您可以使用String.split僅采用第一個元素和與[;-]匹配的[;-]正則表達式來實現此目的; -字面意思:

String res = "abc-xyz;".split("[;-]")[0];
System.out.println(res);

或者使用replaceAll(?s)[;-].*$正則表達式(匹配第一個;-然后任何直到字符串末尾的內容:

res = "abc-xyz;".replaceAll("(?s)[;-].*$", "");
System.out.println(res);

IDEONE 演示

我找到了沒有刪除分組的解決方案。

  • (?<string>.*?)匹配下一個分組模式之前的所有內容
  • (?:-.*?)? 后跟一個非分組模式,以-開頭,然后是零或一次。
  • ; 結束字符。

所以把所有東西放在一起:

    public static final Pattern findString = Pattern.compile("^(?<string>.*?)(?:-.*?)?;$");
    if(findString.find())
    {
       return findString.group("string"); //cant change anything here.
    }

暫無
暫無

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

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