简体   繁体   中英

Regex to remove a non-alphanumeric character at the end of a string which also appears else where in the string

I am not good at Regex and need help creating expression to remove the '/' character at the end of a pageUrl: https://qa.test.celtic.com/ I have tried a few expressions but each time it either removes all the '/' characters or none. The string may change but the last '/' will always be present. Have used [a-zA-Z:/.]$ but it returns the '/' character only. I could the find the character in the string as a substring and then replace in the string using code but would rather find a regex expression that just took the string without the trailing character.

why don't you use the TrimEnd() method to remove a specific character at the end of a string?

string url = @"https://qa.test.celtic.com/";
string result = url.TrimEnd('/');

I agree with @fubo , and would use something more appropriate for the job than Regular Expressions.

That said, if you really want to use a regex, you simply look for a / at the end of the string, which is designated in regex as $ :

Regex.Replace("https://qa.test.celtic.com/", "/$", "")

Or if your question is really "how do match the value without the /", then you need a capturing group that finds everything apart from the / at end end:

Regex.Match("https://qa.test.celtic.com/","(?<host>.*)/$").Groups["host"].Value

The string may change but the last '/' will always be present.

You can try like this:

String res = url.Substring(0,url.Length -1);

You can also put a check like

if ( url!=null && url.EndsWith('/') )
{
    String res = url.Substring(0,url.Length -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