简体   繁体   English

Java正则表达式,用于查找特定的字符串

[英]Java Regular Expression for finding specific string

I have a file with a long string a I would like to split it by specific item ie 我有一个长字符串的文件,我想按特定项目拆分它,即

String line = "{{[Metadata{"this, is my first, string"}]},{[Metadata{"this, is my second, string"}]},{[Metadata{"this, is my third string"}]}}"

String[] tab = line.split("(?=\\bMetadata\\b)");

So now when I iterate my tab I will get lines starting from word: "Metadata" but I would like lines starting from: 因此,现在当我迭代选项卡时,我将获得以单词"Metadata"开头的行,但我希望以以下行开头:

"{[Metadata"

I've tried something like: 我已经尝试过类似的东西:

 String[] tab = line.split("(?=\\b{[Metadata\\b)");

but it doesnt work. 但它不起作用。 Can anyone help me how to do that, plese? 有人可以帮我怎么做吗?

You may use 您可以使用

(?=\{\[Metadata\b)

See a demo on regex101.com . 参见regex101.com上的演示


Note that the backslashes need to be escaped in Java so that it becomes 请注意,反斜杠需要在Java转义,以使其变为

 (?=\\\\{\\\\[Metadata\\\\b) 

Here is solution using a formal pattern matcher. 这是使用正式模式匹配器的解决方案。 We can try matching your content using the following regex: 我们可以尝试使用以下正则表达式匹配您的内容:

(?<=Metadata\\{\")[^\"]+

This uses a lookbehind to check for the Metadata marker, ending with a double quote. 这使用后向检查来检查Metadata标记,并以双引号结尾。 Then, it matches any content up to the closing double quote. 然后,它将匹配任何内容,直到右双引号为止。

String line = "{{[Metadata{\"this, is my first, string\"}]},{[Metadata{\"this, is my second, string\"}]},{[Metadata{\"this, is my third string\"}]}}";
String pattern = "(?<=Metadata\\{\")[^\"]+";
Pattern r = Pattern.compile(pattern);
Matcher m = r.matcher(line);

while (m.find( )) {
    System.out.println(m.group(0));
}

this, is my first, string
this, is my second, string
this, is my third string

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

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