简体   繁体   English

我如何删除字符串的可变部分?

[英]c# - How do i remove a variable part of a string?

I would like to remove part of a string. 我想删除字符串的一部分。 It would have to match "/*/cms/" (without the quotes). 它必须匹配“ / * / cms /”(不带引号)。 * would be a wildcard equaling anything except a / key. *将是一个通配符,等于/键以外的任何值。 The string could have more than one match to be removed. 该字符串可能要删除多个匹配项。

This would have to be done in c#. 这必须在c#中完成。 I think this can be done with a regex? 我认为使用正则表达式可以做到吗? But I'm not sure. 但是我不确定。

要匹配的正则表达式是/[^/]*/cms/ ,使用方式如下: new Regex("/[^/]*/cms/").Replace(yourString, "")

using System.Text.RegularExpressions;

Regex.Replace("/some example text/cms/;/some more text/cms/text/cms", "/[^/]+/cms/", "")

Use /[^/]+/cms/ if something must be between the first and second / 's, use /[^/]*/cms/ if //cms/ is a valid match. 如果必须在第一个/第二个/之间加上/[^/]+/cms/ ,如果//cms/是有效的匹配项,请使用/[^/]*/cms/

Look up Regex.Replace . 查找Regex.Replace Hacking the example quickly: 快速破解示例:

string pattern = "/[^/]+/cms/";
string replacement = "";
Regex rgx = new Regex(pattern);
string result = rgx.Replace(input, replacement);

The accepted answer in this question will help you. 在接受答案这个问题会帮助你。 Ensure that you use the Regex.Replace() method to do the pattern matching and replacement. 确保使用Regex.Replace()方法进行模式匹配和替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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