[英]Match the pattern TEXT[0,0]
I have a lot of source codes with SQL queries like below: 我有很多带有SQL查询的源代码,如下所示:
c_query := "SELECT * FROM TABLE WHERE FIELD_NAME_ONE[2] = 'AB' AND FIELD_NAME_TWO[1,8] = 'ABCDEFGH'"
I would like to match these: FIELD_NAME_ONE[2]
and FIELD_NAME_TWO[1,8]
and these patterns must be found between double quotes ( "
). 我想匹配这些: FIELD_NAME_ONE[2]
和FIELD_NAME_TWO[1,8]
,必须在双引号( "
)之间找到这些模式。
Edit 编辑
c_query := "SELECT * FROM TABLE WHERE FIELD_NAME_ONE[2] = 'AB' AND FIELD_NAME_TWO[1,8] = 'ABCDEFGH' AND TESTE[9] = 'XXXXXXXXX' AND FOO = '" + is_an_array[2] + "'" c_query:=“SELECT * FROM TABLE WHERE FIELD_NAME_ONE [2] ='AB'AND FIELD_NAME_TWO [1,8] ='ABCDEFGH'AND TESTE [9] ='XXXXXXXXX'AND FOO ='”+ is_an_array [2] +“' “
It shouldn´t match is_an_array[2] because is not inside the double quotes. 它不应该与is_an_array [2]匹配,因为它不在双引号内。
Here's a regex pattern for what you seek (edited based on comment): 这是您所寻求的正则表达式模式(根据评论编辑):
".*?[A-Z_]+\[\d(,\d)?\].*?"
I made the match non-greedy ( .*?
) in case there are multiple matches on the one line (unlikely, but for completeness...) 我让比赛非贪婪( .*?
),以防一线上有多个比赛(不太可能,但为了完整......)
It's not clear if you want to match just the target field names or the whole SQL. 如果你想只匹配目标字段的名称或整个SQL目前尚不清楚。 If you want to match just the field names alone, use non-capturing groups for the rest: 如果您只想匹配字段名称,请使用非捕获组:
(?:".*?)[A-Z_]+\[\d(,\d)?\](?:.*?")
I'm assuming you want to be able to match more than just those two specific fields, otherwise you wouldn't have gone to the trouble of applying regular expressions: 我假设您希望能够匹配的不仅仅是这两个特定字段,否则您不会遇到应用正则表达式的麻烦:
var tokens = Regex.Matches(sql, "\"([^\"]+)\"");
foreach (Match token in tokens) {
string str = token.Groups[1].Value;
var fields = Regex.Matches(str, @"(\w+\[\d+(,\d+)*\])");
foreach (Match field in fields)
Console.WriteLine(field.Value);
}
This will find any sequence of letters, numbers and underscores followed by square brackets, with 1 or more comma-separated numbers. 这将找到任何字母,数字和下划线的序列,后跟方括号,带有1个或多个以逗号分隔的数字。
If you only want to match a sequence of letters and underscores before the square brackets, ammend the pattern to: 如果您只想在方括号前匹配一系列字母和下划线,请将模式修改为:
@"([a-zA-Z_]+\[\d+(,\d+)*\])"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.