简体   繁体   中英

Regex to extract String between two expressions in java

I have a log file that contains sent and received messages. I want to extract these message using a regular expression. This is an example of log file:

Message recieved:0908082349234 Session: ...
A message is sent: 12344384834

I wrote the following regex to extract the message:

String pattern = "((A message is sent: )|(Message received:))(.*)(( Session:)|$)";

And it doesn't work. I tried many different forms of it but none of them worked. I want to do this using a single regex. Right now I use one regex for sent and another one for received. But there should be a way to use a single regex for both of them!

.* matches greedily. Use non-greedy version ( .*? ):

String pattern = "(A message is sent: |Message received:)(.*?)( Session:|$)";

BTW, the given log file contains a typo. If the log file really contains the typo, you should adjust the regular expression accordingly.

Message recieved:0908082349234 Session: ...
           ^^

try this pattern

"((A message is sent: )|(Message recieved:))(\\d+?)(.*)"

btw. it seems that you 'recieved' is miss matching between your log and your pattern

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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