0

I want to extract sub string from string using regular expression ie. the following input/out list shows what i really want. i need to extract the dept filter conditions from a string. Here the word [dept] is constant.so what the kind of regular expression is useful to extract the sub string in this scenario

    Input------------------------------------------------Output 

    Some conditions And [dept]=IT                        [dept]=IT
    Some conditions And [dept]=IT Or [dept]=Account      [dept]=IT Or [dept]=Account
    Some conditions And [dept] IN ('IT','Account')       [dept] IN ('IT','Account')

    [dept]=IT And some conditions                        [dept]=IT
    [dept]=IT Or [dept]=Account And some conditions      [dept]=IT Or [dept]=Account 
    [dept] IN ('IT','Account') And some conditions       [dept] IN ('IT','Account')
5
  • There are only these strings from where you want to fetch your o/p or there can be other combinations as well similar to your inputs Commented Oct 16, 2014 at 6:19
  • yes but the department values may change. these are the possible combinations, the structure of the string should be like this Commented Oct 16, 2014 at 6:20
  • It seems like you want everything after And in 1st 3 cases and everything before And in last3 cases, Is that what you want? Commented Oct 16, 2014 at 6:22
  • @jadavparesh06 yes sure Commented Oct 16, 2014 at 6:25
  • This looks a lot like extracting information from arbitrary SQL queries, and I'm 99.85% certain that this is not a task you should solve with a regex. Commented Oct 16, 2014 at 6:28

2 Answers 2

2

This might be close to what you are after

(\[dept\]=\w+)( (Or)|(And))?|(\[dept\] IN \(.+?\))

It matches on your sample input like below, grouped in ().

([dept]=IT) 
([dept]=IT Or) ([dept]=Account) 
([dept] IN ('IT','Account'))

In your script you can join the groups on each line, ie., join ([dept]=IT Or) ([dept]=Account)

But if like suggested in the comments you are indeed parsing SQL, there are SQL parsers that will give you accurate access to your query WHERE expression.

Sign up to request clarification or add additional context in comments.

Comments

1
\[dept\].*(?=\s+\bAnd\b)|\[dept\].*(?=$)

Try this.See demo.

http://regex101.com/r/dZ1vT6/41

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.