我正在做一些字符串解析并想使用正则表达式。我正在迭代字符串,并希望使用正则表达式和偏移量应用诸如“startsWith”之类的内容,如果找到则返回匹配项,否则返回 null。在伪 JavaScript 中:
function startsWith(string, regex, offset) {
if (regex_matches_at_offset) {
return match;
} else {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
一个简单直接的解决方案是先应用子字符串,然后匹配。但我想要使用正则表达式的“startsWith”之类的东西。
如果它是一个字符串而不是正则表达式,我会选择startsWith
function startsWith(string, other_string, offset) {
let starts_with=s.startsWith(other_string, offset); // startsWith from position offset onwards, as other_string has fixed length the "match" is also known
if (starts_with) {
return other_string; // other_string = match
} else {
return null;
}
}
Run Code Online (Sandbox Code Playgroud)
但对于正则表达式,我当前的解决方案(仅用于测试目的)如下所示:
function startsWith(string, regex, offset) {
let end_part=s.substring(offset); // Substring, performance issue
let match=end_part.match(regex); // Match …Run Code Online (Sandbox Code Playgroud) 我想将这个Python代码转换为Lua(nmap脚本):
for i in range(1000, 9999):
if str(i).endswith('9'):
print(i)
Run Code Online (Sandbox Code Playgroud)
我已经走到这一步了:
for var = 1000, 9000 then
if tostring(var).endswith('9') then
print (var)
end
end
Run Code Online (Sandbox Code Playgroud)
但我不知道 Lua 相当于endswith().