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

Time:12-14

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?

CodePudding user response:

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);

CodePudding user response:

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
  • Related