0

I want to map Slug URL with Regex URL mentioned below.

Regex URL - /openPage/*/*
Slug URL -/openPage/{category}/{subCategory}
URL - /openPage/ABC/XYZ

where after pattern matching, I should get like, category = ABC subCategory = XYZ

Any help would be appreciated.

3
  • Look into substrings of regex. You can match and extract substrings using ( and ). Commented Oct 29, 2019 at 9:08
  • Hi @shkschneider, I didn't get. Can you please elaborate? Commented Oct 29, 2019 at 9:13
  • Is there a reason you want to use a regex? They are great if you have a unique pattern match problem to solve, but if it's a standard thing (like URLs) there is almost certainly a library that can do it for you more easily Commented Oct 29, 2019 at 9:23

1 Answer 1

3

You should look into matching groups in Regex. They can be used to get specific parts of a regular expression after matching. For more info you can read this. For your use-case you can use the following Regex:

\/openPage\/([^\/]+)\/([^\/]+)

Regular expression visualization

Debuggex Demo

And here's how you can do that in Kotlin:

val regex = "\\/openPage\\/([^\\/]+)\\/([^\\/]+)".toRegex()
val match = regex.matchEntire("/openPage/ABC/XYZ")
val category = match?.groups?.get(1)?.value
val subCategory = match?.groups?.get(2)?.value

This way you will have your category and subCategory as String?.

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

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.