我正试图找出格式错误的名称的正则表达式,其中用户将名称和关系作为一个值输入,例如
[Son of Joseph Joestar ] => s/o. Joseph Joestar
问题是,由于没有验证,用户输入了不同的变体,如
s/o,s/,s/Joseph,etc
到目前为止,我已经收到
^(s/o.)(S/o.)(s/o)(S/o)(s/)(S/)w+
- 关系在开头或开头,后面是名称
- 还有3个案例女儿(D/o.(、妻子(W/o.(、父亲(F/o.(
我想知道相应的REGEX来过滤掉关系前缀
提前感谢
也许可以从开始
string foo = "s/o. Joseph Joestar";
// Look (and capture) for SDWF followed by "/" and
// EITHER "o" and maybe "." and maybe a white space
// OR we look ahead (?= ) and see a Upper wordchar followeed by lower word chars.
// look ahead because we do not want to have anything to do with this when replacing
string bar = Regex.Replace(foo, @"^([sSdDwWfF])/(o.?s?|(?=[A-Z]w+))", match =>
{
string relation = match.Groups[1].Value.ToUpper() switch
{
"S" => "Son of",
"D" => "Daughter of",
"F" => "Father of",
"W" => "Wife of",
_ => throw new Exception("Oops")
};
return $"{relation} ";
});