lua usa esquema de expressão regular completo

O esquema de correspondência de strings que vem com lua não oferece suporte total a expressões regulares e não pode corresponder a alguns padrões com ramificações, como abc|123.
Depois de pesquisar, descobri que existem duas soluções simples:

Solução 1) Analisar dados com a ajuda de python e pipe

Crie um novo script python aaa.py, analise os parâmetros de entrada e gere os resultados

import re
import sys
for m in re.finditer("abc|123",len(sys.argv)>1 and sys.argv[1] or "",re.S):
	print("\""+m.group(0)+"\",")

Observe que o resultado de saída é representado como uma string em python aqui, e
a string de origem é passada para python em lua e, em seguida, o resultado retornado é integrado aos dados da tabela por meio de loadstring

f=io.popen("python aaa.py abcdef1234567")
loadstring("t={"..f:read("*a").."}")()
for i,v in ipairs(t) do
	print(v)
end

Cenário 2) Exportar boost regex para lua

  • Use boost regex para fazer expressões regulares
  • Use luabind para ligar a interface
  • Use o intervalo de reforço e o iterador de contêiner compartilhado de reforço para retornar vários resultados correspondentes e manter o tempo de vida

Código C++ do programa host

#include <boost/shared_container_iterator.hpp>
#include <boost/range/iterator_range.hpp>
#include <boost/regex.hpp>
#include <luabind/luabind.hpp>
#include <luabind/iterator_policy.hpp>

typedef std::vector<boost::cmatch> sub_match_list;
typedef boost::shared_container_iterator<sub_match_list> shared_sub_match_list_iter;
static boost::iterator_range<shared_sub_match_list_iter> regex_search_all(boost::regex* self, const char* s)
{
    
    
	boost::cmatch match;
	boost::shared_ptr<sub_match_list> matchs(new sub_match_list());
	for (; boost::regex_search(s, match, *self, boost::match_default); s = match[0].second)
	{
    
    
		matchs->push_back(match);
	}
	return boost::make_iterator_range(shared_sub_match_list_iter(matchs->begin(), matchs), shared_sub_match_list_iter(matchs->end(), matchs));
}

static bool cmatch_is_matched(boost::cmatch* self, int i)
{
    
    
	return self->operator[](i).matched;
}

static std::string cmatch_sub_match(boost::cmatch* self, int i)
{
    
    
	return self->operator[](i);
}

luabind::module(L) [
	, class_<boost::regex>("regex")
		.def(constructor<const char *>())
		.def("search_all", &regex_search_all, luabind::return_stl_iterator)

	, class_<boost::cmatch>("cmatch")
		.def("is_matched", &cmatch_is_matched)
		.def("sub_match", &cmatch_sub_match)
];

Exemplo de uso de regex em lua

r=regex("abc|123")
for m in r:search_all("abcdef1234567") do
	print(m:sub_match(0))
end

Supongo que te gusta

Origin blog.csdn.net/tangyin025/article/details/123542982
Recomendado
Clasificación