我想为以下场景创建正则表达式
name like %name
- 匹配并提取%名称
name like '%name'
- 不应该与它有匹配'在%
name like ' %name'
- 不应该匹配以前的字符是' (忽略空间)
name like%name
匹配并提取%name
这就是我得到的[^']%\ w +但是这个过去的两个案例已经覆盖
答案 0 :(得分:2)
这可能符合您的需求,但它取决于前缀为name like
的字符串。
void Main()
{
var strings = new string[] {"name like %name", "name like '%name'", "name like ' %name'", "name like%name"};
var regex = new Regex("^name like ?(%\\w+)");
foreach (var item in strings)
{
Console.WriteLine($"string: \"{item}\" matches: {regex.IsMatch(item)} extracted: {(regex.Match(item).Groups.Count > 0 ? regex.Match(item).Groups[1].Value : string.Empty)}");
}
//Output:
//string: "name like %name" matches: True extracted: %name
//string: "name like '%name'" matches: False extracted:
//string: "name like ' %name'" matches: False extracted:
//string: "name like%name" matches: True extracted: %name
}
正则表达式分解为:
^name like
:以name like
?
:可选空格
(%\\w+)
:我们的匹配组,挑选[a-zA-Z_]前缀为%