Regular expression to match EOF

Viewed 110408

I have some data that look like this:

john, dave, chris
rick, sam, bob
joe, milt, paul

I'm using this regex to match the names:

/(\w.+?)(\r\n|\n|,)/

Which works for the most part, but the file ends abruptly after the last word, meaning the last value doesn't end in \r\n, \n or ,. It ends with EOF. Is there a way to match EOF in regex so I can put it right in that second grouping?

9 Answers

The answer to this question is \Z took me awhile to figure it out, but it works now. Note that conversely, \A matches beginning of the whole string (as opposed to ^ and $ matching the beginning of one line).

EOF is not actually a character. If you have a multi-line string, then '$' will match the end of the string as well as the end of a line.

In Perl and its brethren, \A and \Z match the beginning and end of the string, totally ignoring line-breaks.

GNU extensions to POSIX regexes use \` and \' for the same things.

As JavaScript RegEx doesn't support the boundary match for final terminator (\Z), you could use the following:

var matchEndOfInput = /$(?![\r\n])/gm;

Basically this would match the end of the line, which is not followed by carriage return or new line characters. In essence it behaves the same way as \Z and can be used with JavaScript RegEx implementation.

If you don't have to capture the line separators, this regex should be all you need:

/\w+/

That's assuming all the substrings you want to match consist entirely of word characters, like in your example.

Maybe try $ (EOL/EOF) instead of (\r\n|\n)?

/\"(.+?)\".+?(\w.+?)$/

Assuming you are using proper modifier forcing to treat string as a whole (not line-by-line - and if \n works for you, you are using it), just add another alternative - end of string: (\r\n|\n|,|$)

Related