Mr Goobri
Mr Goobri

Reputation: 1469

PHP regular expression with or operation

I would like to use a regex over strings like:

1-* or *-2.

This is what I've come up with so far:

"/(.*\-2)||(1\-.*)/"

but it doesn't seem to work - it returns true every time, regardless of my input string.

How can I create a regular expression to match these strings?

Upvotes: 1

Views: 93

Answers (3)

knittl
knittl

Reputation: 265575

Try this (simplistic) version:

/(^1-|-2$)/

If you need to match more specific, add [0-9] at the corresponding positions and maybe another anchor (^$).

/(^1-[0-9]$|^[0-9]-2$)/

Upvotes: 2

Desolator
Desolator

Reputation: 22759

try this you need add ^ and $ to match the whole string:

/^(1-0|0-2)$/

or:

/^(1-.*|.*-2)$/

select whatever suits your needs

Upvotes: 1

Krishna
Krishna

Reputation: 381

Try this ...

"/(.+-\2)|(\1-.+)/"

Upvotes: 2

Related Questions