问题
I am getting data from a continuous buffer of strings staring from "8=XXX to 10=XXX". For suppose the string for the first buffer scan is say :Below is the entire string I got in one scan.
8=FIX.4.2|9=00815|35=W|49=TT_PRICE|56=SAP0094X|10=134|
8=FIX.4.2|9=00816|35=W49=TT_PRICE ----------------here I didn't get the full string
Now I want the string starting from "8=xxx" and ending with "10=xxx|" . I have written a program for that and it's working fine. Now the problem is when I pass the above string for matching I only get the string that is exactly starting from "8=xxx to 10=xxx" and the other part that is not match just gets vomited. I also want the remaining part.
|56=SAP0094X|10=134|-------This is the remaining part of the above vomited string
8=FIX.4.2|9=00815|35=W|49=TT_PRICE|56=SAP0094X|10=134|
In the next buffer scan I will get the string which is the remaining part of the vomited string while pattern matching. Now see , the vomited string in the first search is
8=FIX.4.2|9=00816|35=W49=TT_PRICE
and the vomited string in the next search is
|56=SAP0094X|10=134|
Both these strings are need to be appended as like
8=FIX.4.2|9=00816|35=W49=TT_PRICE|56=SAP0094X|10=134|
which is the full string.
Below is my code:
String text = in.toString(CharsetUtil.UTF_8); //in is a reference to ByteBuf
Pattern r = Pattern.compile("(8=\\w\\w\\w)[\\s\\S]*?(10=\\w\\w\\w)");
Matcher m = r.matcher(text);
while (m.find()) {
String message = m.group();
// I need to get the remaining not matched string and has to be appended to the not matched string in the next search so that I will be getting the whole string starting from "8=xxx to 10=xxx|"
System.out.println("Incoming From Exchange >> "+message);
}
回答1:
You can use groups for that:
public static void main(String[] args) {
String someInput = "XXX-payload-YYY-some-tail";
Pattern r = Pattern.compile("(XXX)(.*)(YYY)(.*)");
Matcher m = r.matcher(someInput);
if (m.matches()) {
System.out.println("initial token: " + m.group(1));
System.out.println("payload: " + m.group(2));
System.out.println("end token: " + m.group(3));
System.out.println("tail: " + m.group(4));
}
}
output:
initial token: XXX
payload: -payload-
end token: YYY
tail: -some-tail
Than you can concatenate the "tail" with a result of the second scan and parse it again
来源:https://stackoverflow.com/questions/45637198/how-to-get-the-remaining-not-matched-string-when-using-pattern-matcher-in-regex