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

combining (?(condition)yes|no) and (?{code})

by halley (Prior)
on Sep 14, 2005 at 14:35 UTC ( #491884=note: print w/replies, xml ) Need Help??

in reply to Splitting strings into words when there are no separators

It took me a bit to get the syntax correct, but there are two special regular-expression features which can be used in combination. (?(condition)yes|no) and (?{code}). The perldoc perlre page explains that they can be combined, but gives no example. I then use the (?!pattern) construct with no pattern to force a backtrack for each non-word.

Here's my example.

use strict; use warnings; my %vocab = map { $_ => 1 } qw/one two three four five six seven eight nine/; my $text = "onetwoeightxfour"; my $finder = qr/ (\w+?) (?(?{ not exists $vocab{$1} }) (?!) | (?=) ) /x; for ($text =~ m/$finder/g) { print $_,$/; }
one two eight four
This particular solution is non-greedy: it finds the shortest known word, and leaves the rest for future matches. A more complicated solution would try harder to consume more letters for an early word if it led to fewer un-matched letters in the long-run: "bekindtostewardessesplease" should find 'stewardesses', not 'stew'. Luckily, one possible solution is simple: change (\w+?) to (\w+), and be patient with the engine as it chugs through the additional backtracking work.

Of course, you can fill the vocabulary hash with whatever you want, or use different code in the (?{code}) construct to achieve the solution. You can also replace the (?=) success case to deal with extra unknown letters between words.

[ e d @ h a l l e y . c c ]

Log In?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://491884]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others contemplating the Monastery: (3)
As of 2017-09-22 03:17 GMT
Find Nodes?
    Voting Booth?
    During the recent solar eclipse, I:

    Results (256 votes). Check out past polls.