我有一个与 C# 中的正则表达式相关的问题。
我想在 "字符之间查找文本。 示例:
Enum resultado = SPDialogBox.Instance.show<ACTION_ENUMs.TORNEO_SORTEAR>("Esto es una prueba");
匹配:Esto es una prueba
但是,在这个例子中
Enum resultado = SPDialogBox.Instance.show<ACTION_ENUMs.TORNEO_SORTEAR>("Esto es una prueba");
pKR_MESAPUESTOASIGNACION.CONFIGTORNEO_ID = Valid.GetInt(dr.Cells["CONFIGTORNEO_ID"].Value);
匹配:Esto es una prueba
但一定不能匹配CONFIGTORNEO_ID
,因为它写在方括号之间([]
)
简而言之,我想匹配双引号 ("
) 字符之间的字符串,但该字符串不能写在方括号 ([]
) 之间。
这是我的代码:
var pattern = "\"(.*?)\"";
var matches = Regex.Matches(fullCode, pattern, RegexOptions.Multiline);
foreach (Match m in matches)
{
Console.WriteLine(m.Groups[1]);
}
该模式匹配 "
字符之间的所有字符串,但我如何修改该模式以排除那些写在方括号之间的字符串?
-- 编辑 ---
还有一个例子:
List<String> IdSorteados = new List<String>();
int TablesToSort = 0;
foreach (UltraGridRow dr in fg.hfg_Rows)
{
if (dr.Cells["MESA_ID"].Value == DBNull.Value && dr.Cells["Puesto"].Value == DBNull.Value && !Valid.GetBoolean(dr.Cells["BELIMINADO"].Value) && (Valid.GetBoolean(dr.Cells["Seleccionado"].Value) || SortearTodo))
TablesToSort++;
}
表达式不得匹配 MESA_ID
(在 Cells["MESA_ID"].Value
中找到)或 Puesto
(在 中找到单元格 ["Puesto"].Value
).它也不能匹配 ].Value == DBNull.Value && dr.Cells[
(在 ["MESA_ID"].Value == DBNull.Value && dr.Cells["Puesto "]
)
我希望我已经表达清楚了我的意图。
最佳答案
简单使用负向回顾:
(?<!\[)
基本上,只匹配前面没有 [
的字符串。 Example here , 代码如下:
String fullCode = "Enum resultado = SPDialogBox.Instance.show<ACTION_ENUMs.TORNEO_SORTEAR>(\"Esto es una prueba\");\r\n"
+ "pKR_MESAPUESTOASIGNACION.CONFIGTORNEO_ID = Valid.GetInt(dr.Cells[\"CONFIGTORNEO_ID\"].Value);";
String pattern = @"(?<!\[)\x22(.*?)\x22";
var matches = Regex.Matches(fullCode, pattern, RegexOptions.Multiline);
foreach (Match m in matches)
{
Console.WriteLine(m.Groups[1]);
}
关于c# - 正则表达式匹配字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10194166/