Regex to match only the first line?

前端 未结 4 1292
自闭症患者
自闭症患者 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

提交回复
热议问题