-1

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?

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Nagaraja JB
  • 729
  • 8
  • 18
  • 1
    You can use the [regex](https://regex101.com/r/jiov1m/1), `\[MSG:(.*?)\]` and extract the value of group(1). [Java demo](https://ideone.com/n7OJ0O). I suggest you learn some basics of regex. – Arvind Kumar Avinash Dec 13 '22 at 18:11
  • 1
    Not my downvote. I suggest you [start here](https://stackoverflow.com/questions/4736/learning-regular-expressions). It's fun to learn the basics of regex. – Arvind Kumar Avinash Dec 13 '22 at 18:18
  • Thank you @ArvindKumarAvinash . This is what i was looking for. I will learn basics. Many thanks. I am unable to accept it as answer. – Nagaraja JB Dec 14 '22 at 04:25
  • You are most welcome, Nagaraja. I have converted my comment into an answer now. – Arvind Kumar Avinash Dec 14 '22 at 09:24

2 Answers2

2

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);
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80
  • I have done this already using indexOf. There are more similar patterns i need to consider. So thought of using regex. many thanks for your suggestion. – Nagaraja JB Dec 14 '22 at 04:21
2

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
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110