【问题标题】:Replacing last characters with a character用字符替换最后一个字符
【发布时间】:2012-05-22 11:10:56
【问题描述】:

我可以拥有这些可能的 slug 字符串

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

它们可以是结尾有数字或没有数字的任何东西。

我想做的例如采取:

this-is-my-post-2-3

然后将末尾的-2-3 替换为=2=3。于是就变成了:

this-is-my-post=2=3

那么有没有一种干净的方法可以在 linq 中或通过一些字符串解析或其他方式来完成?

【问题讨论】:

    标签: c# .net string linq


    【解决方案1】:

    您可以使用正则表达式找出字符串的结尾,然后进行正常的字符替换:

    Regex.Replace(slug, @"[\d-]+$", m => m.Value.Replace('-', '='));
    

    快速 PowerShell 测试:

    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
    

    【讨论】:

    • 如果它有这样的字符串 this-is-my-post1
    • 但是,它也会将this-is-my-2nd-post 更改为this-is-my=2nd-post。
    • 那么它不会替换任何东西。如果您有需要担心的极端情况请事先在您的问题中说明。我们回答的只有你给我们的。我们无法读心或有其他通灵能力。
    • 看起来 OP 希望连字符替换为等号,前提是它前面是数字而不是后面。
    • 替换为不同的版本,只会在字符串的末尾替换它们。
    【解决方案2】:

    您可以使用正则表达式来隔离末尾的数字,并替换其中的破折号:

    Regex.Replace(s, @"(-\d+)+$", m => m.Value.Replace('-', '='))
    

    例子:

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-05-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多