0

Hi I need to match a character string which can have 0+ hyphens in between the characters. I'm using PHP preg-match to do this. The characters can be upper or lowercase. Here's a few examples:

TESTTESTtest published successfully
test-TEST-test published successfully
Test-test published successfully

My regex needs to capture all these different cases.

I am going through a log line by line and trying to match the regex below to each line.

This is my current if statement:

if(preg_match('/(\w*) published successfully/',$line,$matches){

}

I just used \w* as my character capture as I didn't need to worry about hyphens before but I need to adapt this to handle the new scenario. Can anyone help me out?

4
  • 2
    Could you please explain what you are doing and why expode("-", $s) does not work? Commented Apr 25, 2017 at 9:38
  • Hi I've added additional information to my initial question, not sure how I would use explode in this instance but I probably didn't have enough information provided before. Commented Apr 25, 2017 at 9:45
  • 2
    Good, haven't you thought of character classes? Like [\w-]*? Do you have to worry about cases like ------ published successfully? Commented Apr 25, 2017 at 9:46
  • Wow that worked perfectly thank you, I don't really know much about regex I'm working off someone else's code so I was struggling to adapt it, I had tried something like ([\w-*]) and it wasn't working but I was clearly typing it out wrong. Thanks so much, I don't need to worry about the edge cases you mentioned what you provided is fine. Thanks again! Commented Apr 25, 2017 at 9:53

1 Answer 1

1

If you do not need to worry about edge cases like ----- published successfully all you need is to add the \w and - to a character class [...] (and I also suggest using a + quantifier to match 1 or more occurrences, not 0 or more, to avoid getting empty matches):

if(preg_match('/([\w-]+) published successfully/',$line,$matches){

}

See the regex demo.

Sign up to request clarification or add additional context in comments.

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.