Conditional regex to distinguish between null and a value

  Kiến thức lập trình

I’m working on a REST api that has a GET endpoint to search for trades in the context of stock exchanges.
It supports dynamic filtering so the client can set the trade field(column), comparison operator and comparison value
he wants.
e.g. Result -eq [Win] or Result -eq [BreakEven]
The operator must start with a dash and the comparison value must be surrounded by square brackets.
Everything within the square brackets will be treated as a value.
e.g. [some-value with whitespaces, "double quotes" and [] within] are totally fine.
Between the three components of the filter there must be at least one whitespace.

The filter is sent as plain string to the backend and gets validated there using regular expressions.

I have already a regex that does this.

s*(?<property>.*?)s+(?<operator>-.*?)s+[(?<comparisonValue>.*?)]s*$

Here are some examples from regex 101

Now, I want to add a null literal so the clients can explicitly search for entries that don’t have a value.
Semantically, everything between the square brackets is treated as a value, but null isn’t a value.
So the brackets must be omitted when comparing to null, like:
Result -ne null

Therefore, my regex needs a condition to match either the null literal (without square brackets) or the value within the square brackets.

I have no experience to speak of regular expressions.
The one that I have was created by googling and trial and erroring.
It is for the validation of the input and not for parsing it.

How can I add a condition to match either a value (in square brackets) or the literal null?

And any suggestions to improve my regex are highly appreciated.

Thanks in advance!

2

Theme wordpress giá rẻ Theme wordpress giá rẻ Thiết kế website

LEAVE A COMMENT