Consecutive pairs
Weekly challenge 131 — 20 September 2021
Week 131: 20 Sep 2021
You are given a string of delimiter pairs and a string to search. Write a script to return two strings, the first with any characters matching the “opening character” set, the second with any matching the “closing character” set.
Example 1: Input: Delimiter pairs: ""[]() Search String: "I like (parens) and the Apple ][+" they said. Output: "([" ")]" Example 2: Input: Delimiter pairs: **//<> Search String: /* This is a comment (in some languages) */ <could be a tag> Output: /**/< /**/>
The task description is not entirely clear, though the examples help a bit.
My approach is to make strings of the opening and closing characters and then use:
$openers =~ s|[^\Q$opens\E]||g; $closers =~ s|[^\Q$closes\E]||g;
to remove those characters from the input string.
I hope that's what was wanted.
#!/usr/bin/perl use strict; use warnings; use v5.26; my ($delimiter_pairs, $search_string, $openers, $closers); # loop over input values until (eof(DATA)) { $delimiter_pairs = <DATA>;; $search_string = <DATA>; chop($delimiter_pairs, $search_string); do_task(); } sub do_task { my ($openers, $closers, $opens, $closes); # copy the search string $openers = $closers = $search_string; # pick off the delimiters in pairs and make strings of the opening and closing characters while ($delimiter_pairs =~ m|(.)(.)|g) { $opens .= $1; $closes .= $2; } # remove all but the opening characters from $openers and similarly with $closers $openers =~ s|[^\Q$opens\E]||g; $closers =~ s|[^\Q$closes\E]||g; say qq[\nDelimiter pairs: $delimiter_pairs]; say qq[Search string: $search_string]; say qq[Openers: $openers]; say qq[Closers: $closers]; } __DATA__ ""[]() "I like (parens) and the Apple ][+" they said. **//<> /* This is a comment (in some languages) */ <could be a tag> {}##^! {note 1} #danger# ^switch off power first! #by order#
Delimiter pairs: ""[]() Search string: "I like (parens) and the Apple ][+" they said. Openers: "([" Closers: ")]" Delimiter pairs: **//<> Search string: /* This is a comment (in some languages) */Openers: /**/< Closers: /**/> Delimiter pairs: {}##^! Search string: {note 1} #danger# ^switch off power first! #by order# Openers: {##^## Closers: }##!##
Any content of this website which has been created by Peter Campbell Smith is in the public domain