Composed Regular Expressions - breaking a regex down into a readable form

后端 未结 3 1422
不思量自难忘°
不思量自难忘° 2021-01-26 07:39

I was reading an article put together by Martin Fowler regarding Composed Regular Expressions. This is where you might take code such as this:

const string patt         


        
3条回答
  •  时光说笑
    2021-01-26 08:13

    I deal with this in PHP by using associative arrays and PHP's version of the tr function (I assume a similar data structure and function exists in any language).

    The array looks like this:

    $mappings = array ( 
      'a' => '[a-z0-9]',
      'd' => '[0-9]', 
      's' => '\s+', //and so on 
    );
    

    Then when I put them to use, it's just a matter of merging with the tr function. Mapped stuff gets converted, and unmapped stuff falls through:

     $regexp = strtr( $simplified_string, $mappings) ;
    

    Bear in mind that this approach can just as easily overcomplicate things as it can simplify them. You're still writing out patterns, it's just that you've abstracted one pattern into another. Nevertheless, having these poor-man's character classes can be useful in outsourcing regexp's to devs or spec providers that don't speak the language.

提交回复
热议问题