开发者

string.find with new lines

Why string.find returns nil in this case?

local str = -- some string with several lines
local pos = string.find(str, 开发者_如何学Go"\r\n")

I'm sure the string contains new line sequence \r\n.

I even tried searching for \r, \n but also \\r\\n.

Turning off pattern matching didn't help

Edit: The string str is loaded from a file.


some string with several lines

If this is done using Lua's [[]] syntax, the resulting Lua string will not have \r\n's in them, even if you save the Lua file as Dos text. This is in accord with Section 2.1 of the Lua Reference manual.


So you're loading the string from a file. Lua uses C-standard io for file access. Your io.open will more or less call fopen. And fopen defaults to doing text translation, so it will convert \r\n to \n for you. If you don't want this, then you need to suffix io.open's "mode" string with "b", as stated in Section 5.7 of the Lua Reference manual.

Why do you even want to search for \r\n anyway? Why not just search for \n?


How sure are you?

$ ./lua
Lua 5.1.4  Copyright (C) 1994-2008 Lua.org, PUC-Rio
> str="hello\r\nworld"
> pos = string.find(str, "\r\n")
> print (pos)
6


What OS are you using, and what mode are you opening the file in (the second parameter to io.open)? If you're opening it as text ('r' or 'w' mode specifiers without b - if unspecified, io.open will use 'r'), Windows will convert all '\r\n' instances when reading from a file file handle to '\n', so you would want to look for '\n'.

If you really need Windows to preserve '\r\n', you have to include the binary specifier when you open the file to suppress this conversion:

local file = io.open('filename.txt','rb') --note the 'b'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜