Regex: How To Group The First Line, And Then Another Group With Everything else?
How can I write 开发者_开发技巧a regex that will put the first line in a group, and then everything else in a second group?
Depending on flavor, something like this should work: (?-s)(.*)(?s)(.*)
. This matches and captures (.*)
twice, the first with "single-line" mode switched off, and the second with it switched on. You may even want to anchor the whole pattern within \A
and \Z
.
In Java:
String text =
"first line\r" +
"second line\r\n" +
"third line etc";
System.out.println(
text.replaceFirst(
"(?-s)(.*)(?s)(.*)",
"FIRST <<<$1>>>\nREST <<<$2>>>"
)
);
This prints (as seen on ideone.com):
FIRST <<<first line>>>
REST <<<
second line
third line etc>>>
Depending on what you're actually doing (e.g. reading a file line by line), probably much better solution exists.
Since .
does not match newline characters if you do not set the dotmatchesall (or singleline) flag, you can simply do
(.*)\r\n([\s\S]*)
Note that \r\n
needs to be changed to whatever your files uses for its newline flag. That would be \n
on Linux or \r
on Macs (according to the Wikipedia).
/\A([^\n]*)\n(.*)\Z/s
This seems to work:
^(.*)$([\s\S]*)
精彩评论