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"
In reply to Re: Need a Regular Expression that tests for words in different order and captures the values found.
by furry_marmot
in thread Need a Regular Expression that tests for words in different order and captures the values found.
by greatwazzoo
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |