簡體   English   中英

正則表達式檢查字符串是否匹配特定模式

[英]Regular expression to check if a string match certain pattern

如何使用 Java 正則表達式檢查字符串是否遵循特定模式? 例如,檢查消息是否首先以“ In the morning ”開頭,然后是任何單詞,然后是“ In the afternoon ”,然后是任何單詞。

我試圖查找正則表達式語法,但發現它很難理解。

我曾嘗試使用| ,但這是一個“或”運算符。 並且沒有指定先匹配“ In the morning ”再匹配“ In the afternoon ”的順序。

Pattern pattern = Pattern.compile("\\bIn the morning\\b|\\bIn the afternoon\\b");
Matcher matcher = pattern.matcher("In the morning I read the news, then I start my work. In the afternoon I have my lunch.");

^In the morning .*In the afternoon.*

^ 匹配要匹配的表達式的開頭。 .* 匹配零個或多個非返回字符。

您還可以在 .* 周圍加上括號以形成捕獲組,以找出您在上午和下午實際執行的操作

^In the morning (.*)In the afternoon (.*)

正則表達式101

String str = "In the morning I read the news, then I start my work. In the afternoon I have my lunch.";
Pattern pattern = Pattern.compile("^\\bIn the morning\\b.*\\bIn the afternoon\\b.*$");
Matcher matcher = pattern.matcher(str);

if (matcher.matches())
    System.out.println("match");
else
    System.err.println("not match");
  • ^斷言行首的位置
  • \\b在單詞邊界處斷言位置: (^\\w|\\w$|\\W\\w|\\w\\W)
  • . 匹配任何字符(行終止符除外)
  • *匹配前一個令牌在零次和無限次之間,盡可能多次,根據需要回饋(貪婪)
  • $在行尾斷言位置

我認為您希望.*介於兩個短語之間,而不是交替使用。 試試這個版本:

Pattern pattern = Pattern.compile("\\bIn the morning\\b.*\\bIn the afternoon\\b");
Matcher matcher = pattern.matcher("In the morning I read the news, then I start my work. In the afternoon I have my lunch.");
if (matcher.find()) {
    System.out.println(matcher.group());
}

這打印:

In the morning I read the news, then I start my work. In the afternoon

暫無
暫無

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

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