Reputation: 12304
I can have these possible slug strings
my-post
my-post-2
my-post-2-3
my-post-2-3-4-5-6-7-8-9
this-is-my-post
this-is-my-post-2
this-is-my-post-2-3
this-is-my-post-2-3-4-5-6-7
abc-abc-abc1
abc-abc-abc1-2
abc-abc-abc1-2-3-4-5-6
They can be anything with number or no numbers at the end.
What I want to do for example take:
this-is-my-post-2-3
Then replace -2-3
at the end with =2=3
. So it becomes:
this-is-my-post=2=3
So is there a clean way I can do it in linq or by some string parsing or something else?
Upvotes: 2
Views: 960
Reputation: 700840
You can use a regular expression to isolate the digits at the end, and replace the dashes in it:
Regex.Replace(s, @"(-\d+)+$", m => m.Value.Replace('-', '='))
Example:
this-is-my-2nd-post -> this-is-my-2nd-post
this-is-my-2nd-post-1 -> this-is-my-2nd-post=1
this-is-my-2nd-post-4-5-6 -> this-is-my-2nd-post=4=5=6
Upvotes: 3
Reputation: 354854
You can use a regular expression to figure out the end of the string and then do a normal replace of characters:
Regex.Replace(slug, @"[\d-]+$", m => m.Value.Replace('-', '='));
Quick PowerShell test:
PS> $strings | %{ [Regex]::Replace($_, '[\d-]+$', {$args[0].value.replace('-','=')}) }
my-post
my-post=2
my-post=2=3
my-post=2=3=4=5=6=7=8=9
this-is-my-post
this-is-my-post=2
this-is-my-post=2=3
this-is-my-post=2=3=4=5=6=7
abc-abc-abc
abc-abc-abc=2
abc-abc-abc=2=3=4=5=6
this-is-my-2nd-post
Upvotes: 9