0

I'm new to perl and having a problem matching a particular portion of a string.

What I'm trying to match is in bold:

[1339300800] CURRENT HOST STATE: Something;

I was successfully able to match the String between the brackets, at least!

($line=~/\[(\d*)\]*/)

I'm trying something like this for the bolded portion:

($line=~/STATE:\s(\S+);/)

Could anyone give some advice?

2
  • Works for me. What's the actual problem? Commented Jun 15, 2012 at 20:39
  • 1
    The answers you are getting are from people who have guessed what the problem is. Your own solution will result in a regex match with $1 containing Something. What is going wrong for you? Commented Jun 15, 2012 at 20:43

3 Answers 3

2

Your regex

STATE:\s([^;]*);

Does work for me. Remember that it is matched in group 1

if ($subject =~ m/STATE:\s(\S+);/) {
    $result = $1;
} else {
    $result = "";
}

Also, the first regex can be made a bit less verbose

\[(\d*)]
Sign up to request clarification or add additional context in comments.

1 Comment

Right, then your solution where you consider ; as the delimeter is a good.
2

If the statement always ends with a ;, you can write:

$line =~ /:\s([^;]+)/

3 Comments

This is what actually worked, not sure why everyone was saying that my code was fine but I still couldnt get it to work, strangely. Thanks for this solution, though!!
@JackieAldama Everyone was testing with "something" but once that string had a space "some thing" your regex would break
In the end this has to be a Good Answer, so +1. But /:\s+([^;]+)/ is probably safer. Or even /:\s+([^;]+?)\s*;/.
1

You're close:

$line =~ /STATE:\s+([^;]+);/

That will get everything that's not a semicolon. Also it will still match if there's more than one space between STATE and "something"

Comments

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.