in reply to Need a Regular Expression that tests for words in different order and captures the values found.
Use a zero-width positive lookahead assertion.
$string = "This is barney rubble and his friends joe rockhead and fred + flintstone"; $string =~ /(?=.*fred (\w+))?(?=.*barney (\w+))?(?=.*joe (\w+))?/; $company = $1 . '_' . $2 . '_' . $3 . '_' . 'inc'; print "$company\n" # "flintstone_rubble_rockhead_inc"
This prints "flintstone_rubble_rockhead_inc". It doesn't fail if one or more names are missing, and keeps the order of your captures -- that is, the word following barney is always $2 (if barney's there), even if fred is missing.
$string = "This is bLarney rubble and his friends joe rockhead and fre +d flintstone"; $string =~ /(?=.*fred (\w+))?(?=.*barney (\w+))?(?=.*joe (\w+))?/; $company = $1 . '_' . $2 . '_' . $3 . '_' . 'inc'; print "$company\n" # "flintstone__rockhead_inc"
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: Need a Regular Expression that tests for words in different order and captures the values found.
by AnomalousMonk (Archbishop) on Jan 15, 2010 at 17:36 UTC | |
by furry_marmot (Pilgrim) on Jan 15, 2010 at 17:57 UTC | |
by AnomalousMonk (Archbishop) on Jan 15, 2010 at 20:11 UTC | |
by furry_marmot (Pilgrim) on Jan 15, 2010 at 20:47 UTC |