Reputation: 477
I have the content as a string:
{1:F01[some data there]}{2:I515[some data there]}{4::[multiple data there]}{5:{TNG:}}
{1:F01[some data there]}{2:I515[some data there]}{4::[multiple data there too]}{5:{TNG:}}
{1:F01[some data there]}{2:I515[some data there]}{4::[some data there]}{5:{TNG:}}
I want to find every record. A record starts with {1} and ends with {5}. I already wrote this regex:
(\{1:F01)?.*(\{2:)?.*(\{5:\{TNG:\}\})?
But i always get the whole content containing every record. What to do?
Upvotes: 2
Views: 673
Reputation: 26677
The regex matches every like because {1
and {5
are made optional with ?
, and the .*
will try to match everything
You can use a simple regex like,
/^\{1:F01.*5:\{TNG:\}\}$/gm
^
Anchors the regex at the start of the string.
{1:F01.*
Matches {1:F01
at the start of the string, followed by anything.
5:\{TNG:\}\}
Matches at the end of the string.
$
Anchors the regex at the end of the string.
Edit
In java, the multiline is added using Pattern.MULTILINE
. If your input string is not multiline, you need not add this flag at all.
Also the regex need not be delimited by //
.
Example
String s="{1:F01[some data there]}{2:I515[some data there]}{4::[some data there]}{5:{TNG:}}";
Pattern p=Pattern.compile("^\\{1:F01.*5:\\{TNG:\\}\\}$", Pattern.MULTILINE);
Matcher m=p.matcher(s);
System.out.println(m.matches());
// true
Upvotes: 1
Reputation: 54303
.*
is greedy, it will match as long as possible, and might glob too many records.
.*?
will stop as soon as possible.
This should do:
\{1:.*?\{5:\{TNG:\}\}
Upvotes: 1