簡體   English   中英

正則表達式匹配字符串java的中間

[英]Regex match in a middle of a string java

我正在編寫一個程序,它以兩個字符串作為輸入,如果第一個字符串存在,則搜索第二個字符串。 要返回 true,第一個 String 必須位於第二個 String 內的單詞中間。 它不能在第二個字符串中開始/結束一個單詞。

示例 1(必須返回true ):

String s1 = "gramm";
String s2 = "Java is a programming langage"

示例 2(必須返回false ):

String s1 = "cook";
String s2 = "Java is not a cooking langage"

這是我的非工作代碼:

 Scanner scanner = new Scanner(System.in);
 String part = scanner.nextLine();
 String line = scanner.nextLine();

 Pattern pattern = Pattern.compile("\\w+"+part+"\\w+",Pattern.CASE_INSENSITIVE);
 Matcher matcher = pattern.matcher(line);
 System.out.println(matcher.matches()) ;

您當前的模式很好,但如果您只想要一個真/假的答案,您可能需要在此處使用String#matches

String s1 = "gramm";
String s2 = "Java is a programming langage";
if (s2.matches(".*\\w" + s1 + "\\w.*")) {
    System.out.println("MATCH");
}
else {
    System.out.println("NO MATCH");
}

更改正則表達式如下。 這適用於所有場景,例如字符串是否包含數字或其他特殊字符。

String part = "cook";
String line = "Java is not a cooking langage";
Pattern pattern = Pattern.compile(".+" + part + ".+",Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(line);
System.out.println(matcher.matches()) ;

if(str1.Contains(str2.toLowercase())) { }

暫無
暫無

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

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