简体   繁体   中英

How to parse OData parameters using regex?

I know this is asked by many people but not solving my issue

I have a odata query

/items?$filter=name eq 'CARPET T!@#&$%^&*()_+-=~<>?,./:";'[]\{}| APE&1-13/32"X42'' or name eq 'Twitter' and subscribers gt '30'&$top=1

I got it a solution but it adds next parameter in last value

(?<Filter>(?<Resource>.+?)\s(?
<Operator>eq|ne|gt|ge|lt|le|add|sub|mul|div|mod|)\s'?(?<Value>.+?)'?)
(?:\s*$|\s+(?:or|and|not))

In last :

**Resource -> subscribers
Operator -> ge
Value -> '30' BUT it give '30'&$top=1**

Since the framing of the question isn't very clear, I assume you wanted Match 3 to give Value -> '30' instead of Value -> '30'&$top=1

You WANT to tell the compiler that there may or may not be a punbctuator like and , or , etc. at the end. But the very last part you added: (?:\\s*$|\\s+(?:or|and|not)) simply tells the compiler that there has to be a conjunction OR zero or more spaces at the end.

You should actually be telling it to match zero-or-more non- ' followed by the end.

Here's the regex you should be using:

(?<Filter>(?<Resource>[^ ]+?)\s(?<Operator>eq|ne|gt|ge|lt|le|add|sub|mul|div|mod|)\s(?<Value>'.+?'))\s*(?:[^']*$|\s+(?:or|and|not))

You can view the regex and its result at https://regex101.com/r/saVoqW/1

All you need to do is change the \\s*$ to [^']*$ and remove the ? after the quotes and you're good to go!

Edit

I noticed that in match 2, the 'Resource' attribute was returning ' name' (with a space at the starting), so I changed <Resources>.+? to <Resources>[^ ]+? , thereby solving the problem :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM