Reputation: 2092
I am trying to learn Regex and I have scenario where I thought I can use the same. I have a set of strings in the below format(as shown in the table) from which I need to extract each substring around joining operator "and", "or", "not". For eg:- "some column name1 = some value1" as one such substring from first string.
After that I need to extract left hand side string and right hand side string of operators "like", "=", "<", ">". In the above example it would give "some column name1" as one substring and "some value1" as another substring along with operator as "=".
- some column name1 = some value1 and some column name2 < another value2 or some column name 3 > value3 not column name 4 = value4 and name5 = value5
- columnA = 324324
- columnB like a text
- value text
Since I am new to Regex, this is what I have tried till now but it doesn't seem to give me all the values around these operators. Once this works, I am thinking I can apply similar regex with operators as "like", "=", "<", ">" on the resulting substrings to get final output.
(.*?)\b(and|or|not)
When I try the above regex on the first example, this part "name5 = value5" is missing after matching.
(.+?)(and|or|not)(.+)
When I try this one, it matches the first substring but rest of them are matched as a single substring instead of splitting those again.
Please note that I was able to use split operation and give "and|or|not" as separator to get array of substrings however I am trying to see if I can directly get these matched substrings from the given string just for learning regex(This answer says it is possible to do using Regex). I have explored stackoverflow for similar questions but none of the solutions worked in my case. The language in my case is Objective C/Swift.
Upvotes: 1
Views: 1257
Reputation: 626738
You may add an end of string anchor $
as an alternative to the delimiters.
(.*?)(?:\b(and|or|not)\b|$)
^^
See the regex demo.
If your string contains line breaks, you must make .
match them by adding (?s)
, a DOTALL modifier, at the pattern start.
Upvotes: 1