Regex matching multiple lines multiple times

前端 未结 2 1552
遇见更好的自我
遇见更好的自我 2021-01-26 13:35

I have a string like this:

Name: John Doe

Age: 23

Primary Language: English

Description: This is a multiline
description field that I want 
to capture

Countr         


        
相关标签:
2条回答
  • 2021-01-26 13:58

    Here's one solution: http://rubular.com/r/uDgXcIvhac.

        \s*([^:]+?)\s*:\s*(.*(?:\s*(?!.*:).*)*)\s*
    

    Note that I've used a negative lookahead assertion, (?!.*:). This is the only way you can check that the next line doesn't look like a new field, and at the same time continue where you left off. (This is why lookaheads and lookbehinds are known as zero-width assertions.)

    EDIT: Removed bit about arbitrary-width lookaheads; I was mistaken. The above solution is fine.

    0 讨论(0)
  • 2021-01-26 14:20

    Would PHP's strtok help you? You could use it with ":" as the delimeter/token and trim leading and trailing spaces to remove the unwanted new lines.

    http://php.net/manual/en/function.strtok.php

    0 讨论(0)
提交回复
热议问题