简体   繁体   English

Java - 检查是否以特定字符开头和结尾的正则表达式

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

Considering a string in following format,考虑以下格式的字符串,

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

How to write regex to check if the line has '[MSG:' followed by some message & ']' and extract text 'information' from above string?如何编写正则表达式来检查该行是否有 '[MSG:' 后跟一些消息 & ']' 并从上面的字符串中提取文本 '信息'?

Your requirement would be something like你的要求是这样的

/\[MSG:.+\]/ in standard regex notation. /\[MSG:.+\]/ 在标准正则表达式中。 But I would suggest to you that you could use String.indexOf to extract your information但我建议你可以使用 String.indexOf 来提取你的信息

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).您可以使用正则表达式\[MSG:(.*?)\]并提取 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 : Output :

information

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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