Phate01
Phate01

Reputation: 1795

Match a char once not knowing its position

I have to match the sql LIKE operator, which have % in its argument. I want to get the argument of the operator, with no %, in php (PCRE regex)

My string to be matched can be something like

field LIKE %?
field LIKE ?%
field LIKE %?%

? is the argument that will be replaced.

My problem is that % can be at the right of ?, or at its left, or both, I have to match it at least once.

I tried with \s*(%?\?%?) to match only the argument, but it works also with no %

Upvotes: 1

Views: 30

Answers (1)

karthik manchala
karthik manchala

Reputation: 13640

You can use this %(\?)|(\?)%

Explanation:

  • %(\?) looks for % left side (matches both %? and %?%)
  • (\?)% looks for % right side (matches both ?% and %?%)

Covers all the cases required.

See Demo

EDIT:-

If you want to replace just ? use (?<=%)(\?)|(\?)(?=%)

DEMO with substitution

Upvotes: 2

Related Questions