簡體   English   中英

在Java正則表達式中匹配錯誤的模式

[英]Matching wrong pattern in regular expressions in java

我試圖在等號前只捕獲一個單詞,但是正在發生的事情是它在等號前捕獲了所有單詞。 這是我的代碼:

 public static void main(String[] args)
  {
    String text      = "This is = an equal sign";

    Pattern p  = Pattern.compile(" (.*?)=");
    Matcher matcher  = p.matcher(text);  
    if (matcher.find())
    {
         System.out.println("Match: " + matcher.group(0));
    }
}

這是我得到的輸出:

匹配:這是=

試試下面的代碼:

class Ideone
{
    public static void main(String[] args)
  {
    String text      = "This is = an equal sign";

    Pattern p  = Pattern.compile("(\\w+)\\s?=");
    Matcher matcher  = p.matcher(text);  
    if (matcher.find())
    {
         System.out.println("Match: " + matcher.group(1));
    }
}
}

輸出:匹配:是

暫無
暫無

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

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