[英]Replace and remove a string via regex
This is first time I am working with regex. 这是我第一次使用正则表达式。
The string below 下面的字符串
var value ="abc ltd as yes"
need to be change to 需要更改为
var value ="abc Limited"
I have the following code: 我有以下代码:
public static string Attempt_Prefix_Removal( string prefix, string replacement, bool remove = false)
{
if (remove == true)
{
var yesy = $"(?<!prefix )" + prefix + ".*";
var test = Regex.Replace(prefix.ToLower(), $"(?<!prefix )" + prefix + ".*", replacement );
}
var output = (remove == true) ? Regex.Replace(prefix.ToLower(), $"(?<!prefix )" + prefix + ".*", replacement) : Regex.Replace(prefix.ToLower(), $"(?<!prefix )" + prefix + "", replacement);
return output;
}
the values that are passed to the method are 传递给方法的值是
prefix ="ltd", replacement = "Limited" , remove = ture
after running the code the result is 运行代码后,结果是
abc Limited as yes
what do i need to change to get ride of as yes
?? 我需要什么来改变得到的乘坐as yes
? thanks 谢谢
private string regexOp(string sentence, string word, string wordtoReplace, bool isRemove)
{
var retValue = sentence;
if (isRemove)
{
var Pattern = "^.*?(?=" + word + ")";
Match result = Regex.Match(sentence, @Pattern);
if (!string.IsNullOrEmpty(result.Value))
retValue = result + wordtoReplace;
}
else
retValue = Regex.Replace(sentence, word, wordtoReplace);
return retValue;
}
try this method, this will work as you expected with dynamic, do not forget to mark it as answer if this really helped you, 尝试这种方法,它将与您期望的动态效果一起使用,如果确实对您有所帮助,请不要忘记将其标记为答案,
You may leverage this code: 您可以利用此代码:
var prefix ="ltd"; var replacement = "Limited";
var pat = $@"(?s)(?<!\w){Regex.Escape(prefix)}(?!\w){remove ? ".*" : string.Empty}";
return Regex.Replace(val, pat, replacement.Replace("$", "$$"));
See the C# demo online 在线观看C#演示
The main points here are: 这里的要点是:
(?s)
- will allow .
(?s)
-将允许.
match a newline (in case you will use .*
in the pattern) 匹配换行符(以防您在模式中使用.*
) (?<!\\w){Regex.Escape(prefix)}(?!\\w)
- the (?<!\\w)
negative lookbehind will fail the match if the current location is preceded with a word char (you may further tweak the lookbehind pattern as per your requirements) (?<!\\w){Regex.Escape(prefix)}(?!\\w)
- (?<!\\w)
负向后搜索将失败,如果当前位置前面有单词char(您可以进一步(?<!\\w){Regex.Escape(prefix)}(?!\\w)
根据您的要求调整后向模式 {remove ? ".*" : string.Empty}
{remove ? ".*" : string.Empty}
- this will either append .*
(if remove
is true ) or not. {remove ? ".*" : string.Empty}
-这将附加.*
(如果remove
为true )。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.