簡體   English   中英

在Java中匹配字符串

[英]Matches in a string in Java

我有以下代碼:

String string = "40' & 40' HC";
if(string.matches("&"))
   System.out.println("Found");

但是條件不是真的。 為什么? 感謝幫助。 謝謝

String.matches(String)用於正則表達式。 我建議您添加一個else (和{} ),我相信您想要contains和類似

if (string.contains("&")) {
    System.out.println("Found");
} else {
    System.out.println("Not found");
}
String string = "40' & 40' HC";
if(string.contains("&"))
 System.out.println("Found");

用.contains替換.matches,我相信您正在嘗試檢查字符串中的字符。

在JAVA中,它被誤命名為.matches()方法。 它嘗試並匹配所有輸入。

String.matches返回整個字符串是否匹配正則表達式,而不僅僅是任何子字符串。

使用Pattern

String string = "40' & 40' HC";
Pattern p = Pattern.compile("&");
Matcher m = p.matcher(string);
if (m.find())
  System.out.println("Found");

暫無
暫無

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

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