3

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!

1
  • what does not work exactly? Commented Dec 25, 2013 at 10:25

2 Answers 2

1

.* 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: ...
           ^^
Sign up to request clarification or add additional context in comments.

4 Comments

This doesn't match the first one.
@hwnd, IMHO, removing space does not make different because the log file contains space before Session.
I was just letting you know =)
Thanks! This one worked. Just a comment! I used matcher.group() and the result contained "A message is sent:" at beginning and "Session:" at the end. Then I changed it to matcher.group(2) and I got my result!
0

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

1 Comment

That was a typing mistake!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.