简体   繁体   中英

Regex to match last character in string - C#

How can I remove the last ';' in a string?

In case of comment at the end of the string I need to return the ';' before the comment.

Example :

"line 1 //comment
line2;
extra text; //comment may also contain ;." 

You didn't wrote what you wanna do with the character, so I give you a solution here that replaces the character:

string pattern = "(?<!//.*);(?=[^;]*(//|$))";
Console.WriteLine(Regex.Replace("line 1 //comment", pattern, "#"));
Console.WriteLine(Regex.Replace("line2;", pattern, "#"));
Console.WriteLine(Regex.Replace("extra; text; //comment may also contain ;.", pattern, "#"));

Output:

line 1 //comment
line2#
extra; text# //comment may also contain ;.

This is slightly ugly with Regex, but here it is:

var str = @"line 1 //comment

line2; test;

extra text; //comment may also contain ;.";

var matches = Regex.Matches(str, @"^(?:(?<!//).)+(;)", RegexOptions.Multiline);
if (matches.Count > 0)
{
    Console.WriteLine(matches[matches.Count - 1].Groups[1].Index);
}

We get a match for the last semicolon in each line (that isn't preceded by a comment), then we look at the last of these matches.

We have to do this on a line-by-line basis, as comments apply for the whole line.

If you want to process each line individually (your question doesn't say this, but it implies it), then loop over matches instead of just looking at the last one.

If you want to replace each semicolon with another character, then you can do something like this:

const string replacement = "#";
var result = Regex.Replace(str, @"^((?:(?<!//).)+);", "$1" + replacement, RegexOptions.Multiline);

If you want to remove it entirely, then simply:

var result = Regex.Replace(str, @"^((?:(?<!//).)+);", "$1", RegexOptions.Multiline);

If you just want to remove the final semicolon in the entire string, then you can just use string.Remove :

var matches = Regex.Matches(str, @"^(?:(?<!//).)+(;)", RegexOptions.Multiline);
if (matches.Count > 0)
{
    str = str.Remove(matches[matches.Count - 1].Groups[1].Index, 1);
}

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