Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to extract String between two expressions in java

Tags:

java

string

regex

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!

like image 211
elahehab Avatar asked Aug 25 '26 16:08

elahehab


1 Answers

.* 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: ...
           ^^
like image 102
falsetru Avatar answered Aug 28 '26 07:08

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!