Sebastien Robert
Sebastien Robert

Reputation: 331

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. (Can be different). I want to determine the part between ' and ' like '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.?].? ]

Upvotes: 2

Views: 120

Answers (4)

Reinderien
Reinderien

Reputation: 15283

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)? \]");

Upvotes: 0

TheVillageIdiot
TheVillageIdiot

Reputation: 40527

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
}

Upvotes: 1

Rohan Singh
Rohan Singh

Reputation: 21535

\[[^']*?'([^']+)

The o_Module.id value would be in the first capturing group.

Upvotes: 0

Ed Swangren
Ed Swangren

Reputation: 124760

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? From what I see in your description using regular expressions here is overkill.

Upvotes: 3

Related Questions