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

后端 未结 3 1428
不思量自难忘°
不思量自难忘° 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:25

    It is fairly easy to read if you can have extended syntax.

    /^
      score   \s+ (\d+) \s+
      for     \s+ (\d+) \s+
      nights? \s+  at   \s+ (.*)
    /x
    

    I personally prefer Perl 6 style regex. I think they're easier to read.

    rule pattern{
      score        $= [ <.digits>+ ]
      for          $=[ <.digits>+ ]
      night[s]? at $= [ .+ ]
    }
    

    After you perform a match against that rule $/ is associated with the matched text.

    So something like this:

    say "Hotel $/";
    say $/.perl;
    

    Would output something like this

    Hotel name of hotel
    {
      'hotel'  => 'name of hotel',
      'nights' => 5,
      'score'  => 8
    }
    

提交回复
热议问题