仅从字符串末尾获取标点符号

Nic*_*ick 2 c#

我正在寻找一个C#片段来删除和存储字符串末尾的任何标点符号.

例:

  • 测试!会回来的!
  • 测试;; 会回来;;
  • 测试?:?会回来吗?:?

  • !!测试!?!会回来的!?!

我现在有一个相当笨重的解决方案,但想知道是否有人可以提出一个更简洁的方法来做到这一点.

我的puncutation列表是

new char[] { '.', ':', '-', '!', '?', ',', ';' })
Run Code Online (Sandbox Code Playgroud)

Ode*_*ded 7

您可以使用以下正则表达式:

\p{P}*$
Run Code Online (Sandbox Code Playgroud)

这分解为:

\p{P}    - Unicode punctuation
*        - Any number of times
$        - End of line anchor
Run Code Online (Sandbox Code Playgroud)

如果您知道字符串末尾总会有一些标点符号,请使用+效率.

并像这样使用它来获得标点符号:

string punctuation = Regex.Match(myString, @"\p{P}*$").Value;
Run Code Online (Sandbox Code Playgroud)

要实际删除它:

string noPunctuation = Regex.Replace(myString, @"\p{P}*$", string.Empty);
Run Code Online (Sandbox Code Playgroud)


Tim*_*ker 5

使用正则表达式:

resultString = Regex.Replace(subjectString, @"[.:!?,;-]+$", "");
Run Code Online (Sandbox Code Playgroud)

说明:

[.:!?,;-]  # Match a character that's one of the enclosed characters
+          # Do this once or more (as many times as possible)
$          # Assert position at the end of the string
Run Code Online (Sandbox Code Playgroud)

正如Oded建议的那样,使用\p{P}而不是[.:!?,;-]删除所有标点字符,而不仅仅是列表中的标点字符.

要同时"存储"标点符号,您可以拆分字符串:

splitArray = Regex.Split(subjectString, @"(?=\p{P}+$)");
Run Code Online (Sandbox Code Playgroud)

然后splitArray[0]包含标点符号前面的部分和splitArray[1]标点字符.如果有的话.