cagdas
cagdas

Reputation: 117

Regex grouping issue

I need a regex to grouping my strings, but I can't grouping properly.

String must be start "foo/", after end with "login" or "something" + "/" + (set|get).

    ^foo\/(login$|(.*)\/(set|get))

"login" or "something" must be group 1
"set" or "get" must be group 2, if exist.

Test strings:
foo/
foo/login   -match
foo/login/get
foo/sadas/set   -match
foo/sadasf/asd
foo/blabla/get   -match

The grouping should be in the following format.

             Group1          Group2
foo      /   login
foo      /   sadasas     /    set
foo      /   blabla      /    get

Upvotes: 1

Views: 40

Answers (1)

Gurmanjot Singh
Gurmanjot Singh

Reputation: 10360

Try this Regex:

^foo\/(?(?=login)(login)|(.*?)(set|get))$

Click for Demo

Explanation:

  • ^ - asserts the start of the line
  • foo\/ - matches foo/ literally
  • (?(?=login)(login)|(.*?)(set|get)) - If the current position is followed by login, match login and capture it as group 2, else match 0+ occurrences of any character(captured in group 1) followed by either set or get(captured in group 3)
  • $ - asserts the end of the string

Updated solution

^foo\/(login$|(?!login).*?(?=[gs]et))([gs]et)?$

Click for Demo

Just realised that this is very close to Wiktor's Comment

Upvotes: 1

Related Questions