Regex to match only the first line?

前端 未结 4 1203
自闭症患者
自闭症患者 2021-02-01 17:32

Is it possible to make a regex match only the first line of a text? So if I have the text:

This is the first line.
This is the second line. ...

It would matc

相关标签:
4条回答
  • 2021-02-01 18:13

    Yes, you can.

    Example in javascript:

    "This is the first line.\n This is the second line.".match(/^.*$/m)[0];
    

    Returns

    "This is the first line."
    

    EDIT

    Explain regex:

    match(/^.*$/m)[0]

    • ^: begin of line
    • .*: any char (.), 0 or more times (*)
    • $: end of line.
    • m: multiline mode (. acts like a \n too)
    • [0]: get first position of array of results
    0 讨论(0)
  • 2021-02-01 18:13

    There is also negative lookbehind function (PowerGREP or Perl flavor). It works perfectly for my purposes. Regex:

    (?<!\s+)^(.+)$

    where

    • (?<!\s+) is negative lookbehind - regex matches only strings that are not preceded by a whitespace(s) (\s also stands for a line break)
    • ^ is start of a string
    • (.+) is a string
    • $ is end of string
    0 讨论(0)
  • 2021-02-01 18:21

    In case you need the very first line no matter what, here you go:

     \A.*
    

    It will select the first line, no matter what.

    0 讨论(0)
  • 2021-02-01 18:28

    that's sounds more like a job for the filehandle buffer.

    You should be able to match the first line with:

    /^(.*)$/m
    

    (as always, this is PCRE syntax)

    the /m modifier makes ^ and $ match embedded newlines. Since there's no /g modifier, it will just process the first occurrence, which is the first line, and then stop.

    If you're using a shell, use:

    head -n1 file
    

    or as a filter:

    commandmakingoutput | head -n1
    

    Please clarify your question, in case this is not wat you're looking for.

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