简体   繁体   English

C#正则表达式需要帮助

[英]C# Regular Expression need help

I try to find a part of a search word in a string variable with regular expression. 我尝试在带有正则表达式的字符串变量中找到搜索词的一部分。

Here is the string variable content : 这是字符串变量内容:

string s_Var = "[ Object[Key='o_Module.Id'].Text ]"

[, ], ', ', and . [,],','和。 always there , but not Key=, Object and Text. 始终存在,但不包含Key =,Object和Text。 (Can be different). (可以不同)。 I want to determine the part between ' and ' like 'o_Module.Id' 我想确定'和'之间的部分,例如'o_Module.Id'

I only want to take the part between ' and ' 我只想参加'和'之间的部分

Can you help me to determine the pattern i need ? 您能帮我确定我需要的样式吗?

Exemple : 范例:

string s_Original_Text = "[ Object[Key='o_Module.Id'].Text ]"

? = i don't know the value can be =我不知道这个值可以是

[ ?[??'o_Module.?].? [?[??'o_Module。?] ..? ] ]

If the single quotes are always present in the form you have shown above, why not just look for the first index of ' using SubString? 如果单引号始终以您上面显示的形式出现,为什么不只使用SubString查找'的第一个索引? From what I see in your description using regular expressions here is overkill. 根据我在您的描述中使用正则表达式的描述,这是过大的。

try this code: 试试这个代码:

var s = "[['o_Module.Id'].Text]"; 
//"[Object[Key='o_Module.Id'].Text]"; //ALSO MATCHES THIS
var r = new System.Text.RegularExpressions.Regex(@"(\[?.*\[?')(.*)('.*)");
var m = r.Match(s);
if (m.Success)
{
    //0 contains whole string
    Console.WriteLine(m.Groups[2].Value); //Prints o_Module.Id
}

I think that this should usually do it, assuming there's only ever one set of single-quotes: 我认为通常应该这样做,假设只有一组单引号:

System.Text.RegularExpressions.Match result = System.Text.RegularExpressions.Regex.Match("[ Object[Key='o_Module.Id'].Text ]", "'([^']*)'");

If you want to add that optional stuff: 如果要添加该可选内容:

result = System.Text.RegularExpressions.Regex.Match("[ Object[Key='o_Module.Id'].Text ]", @"\[ (?:Object)?\[(?:Key=)?'([^']*)'\]\.(?:Text)? \]");
\[[^']*?'([^']+)

o_Module.id值将在第一个捕获组中。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM