Orsokuma
Orsokuma

Reputation: 622

PHP, RegEx. Can't get the match pattern I'm after

So far, I've tried every combination I can think of, and I just can't figure out/find the right one. I'm after matching a "/me" command within a chatroom I'm currently developing.

The RegEx: /^\/me (.*)(\|)(.*)?$/i

Usage: /me does something /me does something else|Hello!

So far, it matches the second /me command usage (i.e., with the "|" separator) perfectly, but not the first.

Can someone point me in the right direction please? I'm losing my mind here.

I'm after matching "/me does something" and "/me does something|Hello!" whilst dropping the "|" if matched

Upvotes: 1

Views: 45

Answers (1)

maraca
maraca

Reputation: 8743

/^\/me (.*?)(?:\|(.*))?$/i
  1. The first line is no match because it contains no |

  2. You cannot just make the | optional because regex are greedy (adding a ? after + and * makes them non-greedy, ?: makes a group non-capturing)

  3. If you plan to add other commands then it is probably more readable if you only match /^\/me (.*)$/i and handle the rest in a function

Upvotes: 1

Related Questions