2
$\begingroup$

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?

$\endgroup$
2
$\begingroup$

Using Regular expressions, as requested:

StringCases[a1, RegularExpression["struct (.*)[ ]*\{"] :> "$1"]

(* {{"name1 "}, {"name2"}, {"name3"}, {"name4"}, {"name5"}, {"lastStruct"}} *)

$\endgroup$
  • $\begingroup$ i will check the solution tomorrow.Thanx $\endgroup$ – TraceKira Dec 10 '14 at 23:54
  • $\begingroup$ thanx , this solved it and is shorter as hailrutan's solution $\endgroup$ – TraceKira Dec 11 '14 at 21:47
  • $\begingroup$ what does ":> "$1"" do :) ? $\endgroup$ – TraceKira Dec 11 '14 at 21:51
  • $\begingroup$ @timoftebogdan It refers to the first matched substring enclosed in parenthesis (.*) $\endgroup$ – Dr. belisarius Dec 11 '14 at 21:56
  • $\begingroup$ damn , this stuff is freaky :( $\endgroup$ – TraceKira Dec 11 '14 at 22:04
6
$\begingroup$

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:

StringPattern`PatternConvert["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"}} *)
$\endgroup$
  • $\begingroup$ sorry , but I need to use regular expressions like I stated in the title $\endgroup$ – TraceKira Dec 10 '14 at 23:12
  • $\begingroup$ @timoftebogdan See the update. $\endgroup$ – halirutan Dec 10 '14 at 23:30
  • $\begingroup$ @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? $\endgroup$ – halirutan Dec 10 '14 at 23:43
  • $\begingroup$ i will check the solution tomorrow.Thanx $\endgroup$ – TraceKira Dec 10 '14 at 23:53

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.