1

i want a regex that would check only contains of logical expressions: 0-9 == || != && etc...

this is my try so far:

/^([ \-+><0-9])|(&&)|(==)|(\x7C\x7C)|(!=)|(<=)|(>=)$/i

Im not sure how it works

http://regex101.com/r/xE4fY3

10
  • How does it not work?
    – Robin
    Commented May 15, 2014 at 12:22
  • 2
    You're only matching one expression for the whole line, try this: /^(([ \-+><0-9])|(&&)|(==)|(\x7C\x7C)|(!=)|(<=)|(>=))+$/i
    – scragar
    Commented May 15, 2014 at 12:24
  • 1
    regex101.com/r/xE4fY3 @AntonioRagagnin look at this Commented May 15, 2014 at 12:24
  • 2
    I'm a fan of regex101 links, but please give here: example inputs, expected output, actual current output.
    – Robin
    Commented May 15, 2014 at 12:25
  • 2
    Is the string: <0========== allowed ? Commented May 15, 2014 at 12:27

3 Answers 3

3

You're only matching one expression for the whole line, try this:

/^(([ \-+><0-9])|(&&)|(==)|(\x7C\x7C)|(!=)|(<=)|(>=))+$/i
2

I created this little fella.

^\h*(\-?)([0-9]+)\h*(&&|==|\x7C\x7C|!=|<=|>=)\h*([0-9]*)$

The \h* is optional whitespace (spaces, tabs).

Then, the next/first part should be numbes (right?).

At least one Number. Optional negative or positive.

Followed by more optional whitespace.

Followed by the optional logical operators.

Followed by a number.

2

Not so different from Andresch Serj solution, a verbose version ( readable and higthly editable ):

$pattern = '~
    # subpattern definitions
    (?(DEFINE)
        (?<operator> && | [!<>=]?= | \x7C\x7C | [+-<>] )
        (?<operand> -?[0-9]+ )
    )

    # main pattern
    ^ \h* \g<operand> \h* (?: \g<operator> \h* \g<operand> )* \h* $
    ~x';
1
  • this is goooood... , newer new there exsist verbose regular expressions Commented May 15, 2014 at 13:21

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.