Beefy Boxes and Bandwidth Generously Provided by pair Networks
There's more than one way to do things

Alternating Case Regex

by QM (Parson)
on Dec 14, 2019 at 18:44 UTC ( #11110133=CUFP: print w/replies, xml ) Need Help??

Elsewhere I saw a question asking about matching alternating case strings. Here's the regex, and a test script.

It looks a bit clunky, but it works.

Here's the test script:

#!/usr/bin/env perl # Test for alternating case regex use strict; use warnings; # Generate all lower/upper combos up to 5 characters with the characte +rs A-E my @test_strings = qw( a A ab aB Ab AB abc aBc Abc ABc abC aBC AbC ABC abcd aBcd Abcd ABcd abCd aBCd AbCd ABCd abcD aBcD AbcD ABcD abCD aBCD AbCD ABCD abcde aBcde Abcde ABcde abCde aBCde AbCde ABCde abcDe aBcDe AbcDe ABcDe abCDe aBCDe AbCDe ABCDe abcdE aBcdE AbcdE ABcdE abCdE aBCdE AbCdE ABCdE abcDE aBcDE AbcDE ABcDE abCDE aBCDE AbCDE ABCDE ); # test all strings, save them in a hash for sorting later my %results; for my $test (@test_strings) { my $result = $test =~ m/^([a-z]([A-Z][a-z])*[A-Z]?|[A-Z]([a-z][A-Z +])*[a-z]?)$/; $results{$test} = $result; } # print the results, sorted by result for my $key (sort by_result_or_length_or_alpha keys %results) { printf "%10s %d\n", $key, $results{$key}; } exit; sub by_result_or_length_or_alpha { ($results{$b} <=> $results{$a}) or (length($a) <=> length($b)) or ($b cmp $a) }

Here's the output:

a 1 A 1 aB 1 Ab 1 aBc 1 AbC 1 aBcD 1 AbCd 1 aBcDe 1 AbCdE 1 ab 0 AB 0 abc 0 abC 0 aBC 0 Abc 0 ABc 0 ABC 0 abcd 0 abcD 0 abCd 0 abCD 0 aBcd 0 aBCd 0 aBCD 0 Abcd 0 AbcD 0 AbCD 0 ABcd 0 ABcD 0 ABCd 0 ABCD 0 abcde 0 abcdE 0 abcDe 0 abcDE 0 abCde 0 abCdE 0 abCDe 0 abCDE 0 aBcde 0 aBcdE 0 aBcDE 0 aBCde 0 aBCdE 0 aBCDe 0 aBCDE 0 Abcde 0 AbcdE 0 AbcDe 0 AbcDE 0 AbCde 0 AbCDe 0 AbCDE 0 ABcde 0 ABcdE 0 ABcDe 0 ABcDE 0 ABCde 0 ABCdE 0 ABCDe 0 ABCDE 0

Quantum Mechanics: The dreams stuff is made of

Replies are listed 'Best First'.
Re: Alternating Case Regex
by choroba (Archbishop) on Dec 14, 2019 at 19:12 UTC
    I'd probably go with
    which gives the same result.
    map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Log In?

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: CUFP [id://11110133]
Approved by haukex
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2021-09-19 23:54 GMT
Find Nodes?
    Voting Booth?

    No recent polls found