tags:

views:

26

answers:

2

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 match "This is the first line.", whatever the first line is.

+1  A: 

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 firs 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.

polemon
+1  A: 

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
Topera
I don't believe this is what he's looking for...
polemon
@polemon: yes, you're right...I changed my answer.
Topera