Perl Monk, Perl Meditation | |
PerlMonks |
comment on |
( [id://3333]=superdoc: print w/replies, xml ) | Need Help?? |
Did not want to use some convoluted regexp patterns ... Want to learn the tehnique to do such list/hash substitutions ... A common approach to handling long search/replace string lists is to generate the search regex automatically from the keys of the search/replace hash. (Then you just have to worry about getting the hash right!)
Note that none of the conversion examples use the /e switch, which will make conversion slightly faster. In all the conversion examples, F99-9 is never converted: it just doesn't appear in the conversion @keys array. In the first conversion example, the F29-2 substring in FF29-22 and -F29-2- is converted even though it is embedded in another string: it appears in the conversion list. This is fixed for FF29-22 in the second example by using \b boundary assertions to allow conversion only if a search string is neither preceded nor followed by a 'word' character ([A-Za-z0-9_]), but this still allows the substring in -F29-2- to be replaced because '-' is not a word character. This problem (if problem it is) is fixed in the third example by using different boundary assertions: (?<! \S) and (?! \S) allow a match (and replacement) only if the potential match substring is neither preceded nor followed by a non-whitespace character.
Note that | (pipe) and not , (comma) is the alternation metacharacter. Update: aaron_baugher, in a reply already posted, gave an example of the automatic regex generation technique discussed above, but the examples of using boundary conditions to refine a match may still be useful. In reply to Re^3: multiple substitution
by AnomalousMonk
|
|