简体   繁体   中英

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

Considering a string in following format,

[ABCD:defg] [MSG:information] [MSG2:hello]

How to write regex to check if the line has '[MSG:' followed by some message & ']' and extract text 'information' from above string?

Your requirement would be something like

/\[MSG:.+\]/ in standard regex notation. But I would suggest to you that you could use String.indexOf to extract your information

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

You can use the regex , \[MSG:(.*?)\] and extract the value of group(1).

Demo :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM