Reputation: 775
I want to group strings based on character.
For eg. I want to split following url in two groups
group 1 - /viewarticle/abd-fdj-gfg-to
group2 - 628882 (last string)
/viewarticle/abd-fdj-gfg-to-628882
I tried this " -(?!.*-) " but it is not working.
I have to use only regex not split function.
Any help would be appreciated.
Upvotes: 3
Views: 2167
Reputation: 521279
You may try splitting using a lookbehind, e.g. split on:
(?<=-to)-
You could also make the lookbehind more specific:
(?<=abd-fdj-gfg-to)-
But this would only make sense if what precedes -to
would always be the same.
Edit:
If you need to split on the last hyphen, then use the negative lookahead:
-(?!.*-)
Upvotes: 3
Reputation: 37404
You can simply use groups ()
with .*-
to capture the first input and the rest as second so use:
(.*-)([a-zA-Z\\d]+)
val regex = "(.*-)([a-zA-Z\\d]+)".toRegex() // use only (\\d+) for digits
val matchResults = regex.find("/viewarticle/abd-fdj-gfg-to-628882")!!
val (link, id) = matchResults.destructured
println("Link: $link \nID: $id")
Details:
.*-
: match anything till last -
[a-zA-Z\\d]+
: match 0 or more characters a-zA-Z
or digits
Upvotes: 4