OK, I know this must be a simple problem, but right now I'm just stuck and need some advice with this :). I have the following list:

list={"HS004", "HS001", "HM002", "HP003", "HP005", "HS006", "HA008", \
"HA010", "HS011", "HP022", "HA015", "HM016", "Hx012", "HM021", \
"HP027", "HM020", "HP014", "HA034", "HM029", "HS023", "HP041", \
"HM026", "HS018", "HA040", "HS036", "HP030", "HP099", "HA038", \
"HP037", "HM031", "HS045", "HA050", "HP032", "HM033", "HM044", \
"HP025", "HS007", "HM055", "HA035", "HS047", "HP043", "HP056", \
"HS063", "HS052", "HS049", "HP046", "HM053", "HP057", "HP062", \
"HS064", "HP067", "HS074", "HP078", "HA081", "HS091", "HS073", \
"HA065", "HS072", "HS096", "HS080", "HS093", "HS066", "HS095", \
"HS075", "HA103", "HS085", "HS098", "HP108", "HS082", "HP083", \
"HP109", "HP088", "HP090", "HA121", "HP104", "HP100", "HP107", \
"HP111", "HP119", "HP118", "HP110", "HA122", "HS115", "HS092", \
"HS071", "PA001", "PA002", "PA003", "PA004", "PA005", "PA006", \
"PA007", "PA008", "PA009", "PA010", "PA011", "PA012", "PA013", \
"PA014", "PA015", "PA016", "PA017", "PA018", "PA019", "PA020", \
"PA021", "PA022", "PA023", "PA024", "PA025", "PA026", "PA027", \
"DH001", "DH008", "DH003", "DP006", "DP008", "DP010", "DH002", \
"DP012", "DH009", "DP014", "DH005", "DH007", "DH010", "DH011", \
"DP011", "DP013", "DP016", "DP017", "DP021", "DP022", "DP024", \
"DH006", "DH012", "DH013"

I want to select just the Cases with a "H" at the beginning, e.g. HS004, HM021 and so on.

I tried it with this:

 StringCases[list, "H" ~~ __]

but that gives me also strings like DH005, which is not what I want. Those string patterns regularly confuse me :D. So what would be the correct one here?

  • 1
    $\begingroup$ Flatten@StringCases[list, StartOfString ~~ "H" ~~ __ ~~ EndOfString] or Select[list, StringMatchQ[#, "H" ~~ __] &] it is probably a duplicate, help me find it :) $\endgroup$ – Kuba Mar 23 '15 at 11:57
  • $\begingroup$ ah ok..I did not know StartofString and EndofString yet. I searched for a similar post, but could not find anything. Thank you! $\endgroup$ – holistic Mar 23 '15 at 12:01
  • $\begingroup$ I failed to find a duplicate. Here's closely related topic: 4469 $\endgroup$ – Kuba Mar 23 '15 at 12:06
  • $\begingroup$ See also: (6998), (8945), (9911), (25002) $\endgroup$ – Mr.Wizard Mar 23 '15 at 12:17

It does what it is designt to, so either put there a stronger pattern:

Flatten @ StringCases[list, StartOfString ~~ "H" ~~ __ ~~ EndOfString] 

or use more suited functions:

Select[list, StringMatchQ[#, "H" ~~ __] &]
| improve this answer | |
  • $\begingroup$ I marked this as a duplicate of one one you found; I think is does in fact answer this question. $\endgroup$ – Mr.Wizard Mar 23 '15 at 12:18
  • $\begingroup$ @Mr.Wizard Ok, wasn't sure if it was close enough $\endgroup$ – Kuba Mar 23 '15 at 12:19

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