簡體   English   中英

Java - 檢查是否以特定字符開頭和結尾的正則表達式

[英]Java - regular expression to check if begins and ends with certain characters

考慮以下格式的字符串,

[ABCD:defg] [MSG:信息] [MSG2:你好]

如何編寫正則表達式來檢查該行是否有 '[MSG:' 后跟一些消息 & ']' 並從上面的字符串中提取文本 '信息'?

你的要求是這樣的

/\[MSG:.+\]/ 在標准正則表達式中。 但我建議你可以使用 String.indexOf 來提取你的信息

String str = ...
int idx = str.indexOf("MSG:");
int idx2 = str.indexOf("]", idx);
val = str.substring(idx + "MSG:".length(), idx2);

您可以使用正則表達式\[MSG:(.*?)\]並提取 group(1) 的值。

演示

import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
class Main {
    public static void main(String args[]) {
        String str = "[ABCD:defg] [MSG:information] [MSG2:hello]";
        Matcher matcher = Pattern.compile("\\[MSG:(.*?)\\]").matcher(str);
        if (matcher.find())
            System.out.println(matcher.group(1));
    }
}

Output :

information

暫無
暫無

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

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