how to extract the string using regular expressions

I have the list :

a1 = {"struct name1 {","struct name2{","struct name3{","struct name4{",
"struct name5{","struct lastStruct{"}


I tried to extract the struct names "name1",..."lastStruct" with this but I failed hard :(

StringCases[a1, RegularExpression["[^struct^{^\\s]"]]


Which returned:

{{"n", "a", "m", "e", "1"}, {"n", "a", "m", "e", "2"}, {"n", "a", "m", "e", "3"}, {"n", "a", "m", "e", "4"}, {"n", "a", "m", "e", "5"}, {"l", "a", "S"}}

Any ideas?

Using Regular expressions, as requested:

StringCases[a1, RegularExpression["struct (.*)[ ]*\{"] :> "$1"]  (* {{"name1 "}, {"name2"}, {"name3"}, {"name4"}, {"name5"}, {"lastStruct"}} *) • i will check the solution tomorrow.Thanx Dec 10 '14 at 23:54 • thanx , this solved it and is shorter as hailrutan's solution Dec 11 '14 at 21:47 • what does ":> "$1"" do :) ? Dec 11 '14 at 21:51
• @timoftebogdan It refers to the first matched substring enclosed in parenthesis (.*) Dec 11 '14 at 21:56
• damn , this stuff is freaky :( Dec 11 '14 at 22:04

You can use the high-level functions to build your string expression for this:

StringCases[a1, "struct " ~~ name__ ~~ "{" :> name]
(* {{"name1 "}, {"name2"}, {"name3"}, {"name4"}, {"name5"}, {"lastStruct"}} *)


If you really need a RegularExpression then there is nothing simpler than starting with the high-level functions and let Mathematica figure out the dirty details :-)

Observe:

StringPatternPatternConvert["struct " ~~ name__ ~~ "{"]
(* {"(?ms)struct (.+)\\{", {{Hold[name], 1}}, {}, Hold[None]} *)


What you see in the first position of the resulting list is what you need:

StringCases[a1, RegularExpression["(?ms)struct (.+)\\{"] :> "\$1"]
(* {{"name1 "}, {"name2"}, {"name3"}, {"name4"}, {"name5"}, {"lastStruct"}} *)
`
• sorry , but I need to use regular expressions like I stated in the title Dec 10 '14 at 23:12
• @timoftebogdan See the update. Dec 10 '14 at 23:30
• @timoftebogdan Btw, I saw just now that I ignored that there is a space after "name1". I guess you can now fix this yourself, right? Dec 10 '14 at 23:43
• i will check the solution tomorrow.Thanx Dec 10 '14 at 23:53