如何使用正则表达式删除特定字符
本文关键字:字符 删除 何使用 正则表达式 | 更新日期: 2023-09-27 18:02:26
如何解决这个问题?请不要介意数据注释的文本,这只是为了测试。如何删除数据注释?
[SuppressMessage("Microsoft.Globalization", "CA1303:Do not pass literals as localized parameters",
MessageId = "YouSource.DI.Web.Areas.HelpPage.TextSample.#ctor(System.String)",
Justification = "End users may choose to merge this string with existing localized resources.")]
[SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly",
MessageId = "bsonspec",
Justification = "Part of a URI.")]
public int Get1Number([FromBody]string name)
我有这个代码
public void RemovePublicModifier()
{
this.method = this.SanitizeString(this.method, Public);
}
public void RemoveDataAnnotation()
{
int startIndex = this.method.LastIndexOf(']');
var result = this.method.Substring(startIndex + 1).Trim();
this.method = result;
}
private string SanitizeString(string method, string filter)
{
var items = method.Split(' ').ToList();
var publicItem = items.Where(i => i == filter).FirstOrDefault();
if (publicItem != null)
{
items.Remove(publicItem);
}
var result = string.Join(" ", items.ToArray()).Trim();
return result;
}
但是它给了我一个错误的结果。
string name)
我想要的是。
int Get1Number([FromBody]string name)
string inputStr = @"[SuppressMessage(""Microsoft.Globalization"", ""CA1303:Do not pass literals as localized parameters"",
MessageId = ""YouSource.DI.Web.Areas.HelpPage.TextSample.#ctor(System.String)"",
Justification = ""End users may choose to merge this string with existing localized resources."")]
[SuppressMessage(""Microsoft.Naming"", ""CA2204:Literals should be spelled correctly"",
MessageId = ""bsonspec"",
Justification = ""Part of a URI."")]
public int Get1Number([FromBody]string name)";
Console.WriteLine(Regex.Replace(inputStr, @"(^|'s*)'[['s'S]*?']'s*public's+", string.Empty));
public is also removed
试试这个
Regex.Replace(inputStr, @"(?<!'()'[[^']]+']'r'n", string.Empty));
它匹配包含在[]
中的文本,但不匹配前面有(
的文本
您可以尝试执行以下正则表达式替换:
(?ims)^'s*'[(?!'bpublic'b)['s'S]*?')']'s*public's*
用空字符串替换
c#:var result = Regex.Replace(str, @"(?ims)^'s*'[(?!'bpublic'b)['s'S]*?')']'s*public's*", string.Empty);
这是一个演示
尝试使用这个正则表达式,它将消除抑制消息,也支持其他访问修饰符:
('[[^]]+')'])(?<modifiers>'s+'w+'s)?
如果您不想删除访问修饰符,那么只需在Regex.Replace
期间跳过此命名组。
下面的代码将int Get1Number([FromBody]string name)
提取到text
变量。
var input = @" [SuppressMessage(""Microsoft.Globalization"", ""CA1303: Do not pass literals as localized parameters"",
MessageId = ""YouSource.DI.Web.Areas.HelpPage.TextSample.#ctor(System.String)"",
Justification = ""End users may choose to merge this string with existing localized resources."")]
[SuppressMessage(""Microsoft.Naming"", ""CA2204:Literals should be spelled correctly"",
MessageId = ""bsonspec"",
Justification = ""Part of a URI."")]
public int Get1Number([FromBody]string name)";
var match = Regex.Match(input, @"'w+'s+'w+'('[FromBody']'w+'s+'w+')");
var text = match.Groups[0].Value;