简体   繁体   中英

How to remove the last comma and space from string (if there) using regex?

我在C#应用程序中有一个字符串,并想知道检查最后两个字符(逗号和空格)的正确方法是什么,并使用正则表达式删除它们(如果是这样)。

A working solution without regex :

string str = "dfsf, ";

if (str.EndsWith(", "))
    str = str.Remove(str.Length - 2);

We remove 2 because 2 is the length of ", " .

demo

You don't need Regex for that, use String.TrimEnd like:

string updatedString = yourString.TrimEnd(',', ' ');

You can also specify a string and call ToCharArray like:

string str = "something,  ,   ,,,,   ";
string updatedString = str.TrimEnd(", ".ToCharArray());

would give you "something"

If you only want to remove a single occurrence of ", " (comma and space at the end) then use:

if (str.EndsWith(", "))
    updatedString = str.Substring(0, str.Length - 2);

Rather than removing the trailing comma and space it's easier to simply generate the string without an extra comma in the first place. When generating the comma separated values simply use String.Join to join all of the strings together with a particular separator:

var line = string.Join(", ", yourCollectionOfValues);

It'll be easier and faster than appending the values together, and Join will already handle ensure that there is no trailing separator.

(Sorry I was late the the party.)

Yes , this is not something for which you have to or should use a regex; but since you asked how to do it with a regex (eg maybe you are just curious, and "suppose I have to to this with a regex" hypotheticals are a good way to learn), consider the following pattern:

(.*?)(, )?$

You can test it in a related regex fiddle .

Key points:

  • (.*?) – Match zero or more ( * ) of any character except newline ( . ) as few times as possible ( ? ).
  • (, )?$ – Match zero or one ( ? ) , at the end ( $ ).

Also, the following C# example with this pattern...

var str1 = "whatever, ";
var str2 = "whatever, ,";
var str3 = "";

var regex = new Regex("(.*?)(, )?$");
var str1Match = regex.Match(str1);
var str2Match = regex.Match(str2);
var str3Match = regex.Match(str3);

Console.WriteLine(str1Match.Groups[1].Value);
Console.WriteLine(str2Match.Groups[1].Value);
Console.WriteLine(str3Match.Groups[1].Value);

...produces the following outputs:

  • str1 ( "whatever, " ) => whatever
  • str2 ( "whatever, ," ) => whatever, ,
  • str3 ( "" ) =>

It uses Groups[1].Value to get the first capture group's value (ie the value matched by (.*?) rather than (, )? (if any)).

Edit:

I actually like what @UlugbekUmirov suggested in his comment ( string output = Regex.Replace("my string, ", ", $", ""); ) even better because it is super simple; but hopefully you find the approach I outlined instructive.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM