# How to Pick Out Strings of a Specified Length

Suppose I have the following edge set:

edges = {N500122 -> N5003, N50012 -> N1099, N5003 -> N48059, N5003 -> N22007, N234544 -> N5001, N3010->N2111}


I'm looking for this result: N500122->N5003, N5003->N48059, N5003->N22007, N234544->N5001,

The result comes from looking only for a node with ONLY N5xxx; a total of 5 places, where N is always in first place position. For example, the edge N50012 -> N1099 would not be outputted since N50012 has six places. However, the edge N500122->N5003 would be outputted since to the right of the arrow the node N5003 meets the N5xxx requirement. The edge N3010->N2111 would not be outputted since neither side of the arrow has a node of the form N5xxx.

Any assistance would be most welcomed!

edges = {N500122 -> N5003, N50012 -> N1099, N5003 -> N48059,
N5003 -> N22007, N234544 -> N5001, N3010 -> N2111};


Using Cases:

 f1 = StringLength@ToString@# &;

f2 = StringStartsQ[ToString@#, "N5"] &;

Cases[edges, Rule[a_, b_] /; f1@a == 5 && f2@a || f1@b == 5 && f2@b]


{N500122 -> N5003, N5003 -> N48059, N5003 -> N22007, N234544 -> N5001}

Or in a more compact form using only one test:

test = StringMatchQ[ToString@#, "N5" ~~ x___ /; StringLength[x] == 3] &;

Cases[edges, Rule[a_, b_] /; test@a || test@b]


{N500122 -> N5003, N5003 -> N48059, N5003 -> N22007, N234544 -> N5001}

• awesome! many thanks! Commented Jun 28 at 23:10
• You're welcome! It's a pleasure to help :-) Commented Jun 28 at 23:18
edges = {
N500122 -> N5003, N50012 -> N1099, N5003 -> N48059,
N5003 -> N22007, N234544 -> N5001, N3010 -> N2111};


A variant of E. Chan-López' answer

f[x_] :=  With[{s = ToString[x]}, StringLength[s] == 5 && StringStartsQ[s, "N5"]]

Cases[edges, (a_ -> b_) /; f[a] || f[b]]


{N500122 -> N5003, N5003 -> N48059, N5003 -> N22007, N234544 -> N5001}

Another possibility:

Cases[edges, a_ /; f @ a[[1]] || f @ a[[2]]]


same result

• Verrrrry clever!!! ... very much appreciated!! Commented Jun 28 at 23:11
• Thank you, 42700, interesting question :)
– eldo
Commented Jun 28 at 23:21
edges = {N500122 -> N5003, N50012 -> N1099, N5003 -> N48059,
N5003 -> N22007, N234544 -> N5001, N3010 -> N2111};
e = edges /. (a_ -> b_) :> (ToString[a] -> ToString[b]);
q[u_] := StringContainsQ[u, "N5" ~~ __] && StringLength[u] == 5
Pick[e, Or @@@ MapAt[q, List @@@ e, {All, {1, 2}}]]


-> {"N500122" -> "N5003", "N5003" -> "N48059", "N5003" -> "N22007", "N234544" -> "N5001"}

• Outstanding coding ubpdqn ... thank u sharing ur talent! Commented Jun 29 at 19:38