Home > Software design >  PHP regex match any string ending with asterisk
PHP regex match any string ending with asterisk

Time:07-09

I have a php 7 app and I want to match some patterns using regex. I have the following pattern so far:

/=\~|=\*|=|!=|\(\)|>=|<=|>|</

And I'm able to match any of the following:

=~, =*,=,!=...etc.

However, I want to match two more patterns, the first starts with = followed by any number of chars (including numbers and special characters) ending with an asterisk, for example: =ijnhu9* or =1$n*. The second one is = followed by an asterisk followed by any number of chars (including numbers and special characters). For example: =*bfrg%1 or =*7lk;y. How can I add these two new patterns to my original pattern? Thank you.

CodePudding user response:

You can extend the alternation with the parts that you want, and put the most specific ones at the beginning.

=\*[^\s*=]*|=[^\s*=]*\*|=[~*]?|!=|\(\)|[<>]=?
  • =\*[^\s*=]* Match =* optionally followed by any char except = or a whitespace char
  • | Or
  • =[^\s*=]*\* Match = optionanly followed by any char except * or = or a whitespace char, ending on *
  • | Or
  • =[~*]? Match = =~ or =*
  • | Or
  • != Match literally
  • | Or
  • \(\) Match ()
  • | Or
  • [<>]=? Match < > <= >=

Regex demo

  • Related