Beefy Boxes and Bandwidth Generously Provided by pair Networks
more useful options
 
PerlMonks  

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 $_,$/; }
Output:
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?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://491884]
help
Chatterbox?
[stevieb]: it's a long day when you want to make changes to a project and the entire test suite takes 2 hours to fully run :)
choroba knows the situation. At work, unit tests run for 30 minutes, and integration and end-to-end tests take almost one hour.

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (5)
As of 2017-03-26 22:06 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Should Pluto Get Its Planethood Back?



    Results (315 votes). Check out past polls.