3
$\begingroup$

I wish to collect the items in the first list provided the constraints in the second list. For example in the lists shown below the first list shows a bunch of strings and the second list shows the positions of the strings as they appear in a string:

{StringCases[#1, RegularExpression[#2]],
StringPosition[#1,RegularExpression[#2]]} &["tthis is a book fine", "(?:is|book|t)"]

{{"t", "t", "is", "is", "book"}, {{1, 1}, {2, 2}, {4, 5}, {7, 8}, {12, 15}}}

The output I am desperately trying to get should look like as follow:

{"tt","is","is","book"}

The rational behind the result is that since the first two elements are "t" and differ only by one unit which is the distance between them so they occur consecutively i.e. 1+1 = 2.

On the other hand however, the first instance of "is" occupies position 4-5 in the string and the second occurence of "is" is situated at positions 7-8, and is separated by a space (they do not occur consecutively as 4+2 = 6 and not 7). Therefore "is" do not merge.

I am struggling to find a way and would very much appreciate if someone can kindly help me with the problem. Thanks in advance !

$\endgroup$
  • 1
    $\begingroup$ So what is the input, lists or the string? In case of the string, is this what you are after? StringCases["tthis is a book fine", Repeated /@ {"is", "book", "t"}] $\endgroup$ – Kuba Jan 18 '16 at 9:23
  • $\begingroup$ Many thanks !!! Your solution made the second list redundant. I have followed some of your other codes and am fascinated by your knowledge of Mathematica. If you do not mind, may I ask you for your contact details, as in an email. Thanks again ! $\endgroup$ – Ali Hashmi Jan 18 '16 at 9:33
  • $\begingroup$ Thanks :) Let's use SE platform to communicate first :) If you fail to find an answer to your questions you can ask new one, or ask on chat. I'm not the only one who can help :) $\endgroup$ – Kuba Jan 18 '16 at 9:42
2
$\begingroup$

As discussed in comments, we can get the result directly.

StringCases["tthis is a book fine", Repeated /@ {"is", "book", "t"}]
{"tt","is","is","book"}
$\endgroup$

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.