如何在Lua中编写此正则表达式? [英] How to write this regular expression in Lua?

查看:97
本文介绍了如何在Lua中编写此正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是Lua regex等价功能的新手,我需要编写以下正则表达式,该正则表达式应与带小数的数字匹配

I'm new to the Lua regex equivalence features, I need to write the following regular expression, which should match numbers with decimals

\b[0-9]*.\b[0-9]*(?!])

基本上,它匹配十进制格式的数字(例如:1、1.1、0.1、0.11),这些数字不以']'结尾,我一直在尝试使用string.gmatch用Lua编写这样的正则表达式,但是我对Lua匹配表达式没有经验...

Basically, it matches numbers in decimal format (eg: 1, 1.1, 0.1, 0.11), which do not end with ']', I've been trying to write a regex like this with Lua using string.gmatch, but I'm quite inexperienced with Lua matching expressions...

谢谢!

推荐答案

Lua没有正则表达式,主要是因为完整的正则表达式库会比Lua本身更大.

Lua does not have regular expressions, mainly because a full regular expression library would be bigger than Lua itself.

Lua所具有的是匹配模式,功能不那么强大(但对于许多用例仍然足够):

What Lua has instead are matching patterns, which are way less powerful (but still sufficient for many use cases):

  • 没有单词边界"匹配器,
  • 别无选择,
  • 也没有前瞻或类似内容.

我认为没有Lua模式可以匹配字符串的所有可能出现,也没有其他模式可以匹配,这意味着您必须以某种方式解决此问题.

I think there is no Lua pattern which would match every possible occurrence of your string, and no other one, which means that you somehow must work around this.

Stuart提出的模式%d*%.?%d*匹配所有十进制数字(带或不带点),但也匹配空字符串,这不是很有用. %d+%.?%d*将所有十进制数字与点之前(或没有点)至少一位数字匹配,%d*%d.?%d+将所有十进制数字与点之后(或没有点)至少一位数字匹配. %.%d+匹配十进制数字,点前无数字.

The pattern proposed by Stuart, %d*%.?%d*, matches all decimal numbers (with or without a dot), but it also matches the empty string, which is not quite useful. %d+%.?%d* matches all decimal numbers with at least one digit before the dot (or without a dot), %d*%d.?%d+ matches all decimal numbers with at least one digit after the dot (or without a dot). %.%d+ matches decimal numbers without a digit before the dot.

一个简单的解决方案是搜索这些模式中的多个(例如,%d+%.?%d*%.%d+),然后组合结果.然后查看找到它们的地方,并查看它们后面是否有]".

A simple solution would be to search more than one of these patterns (for example, both %d+%.?%d* and %.%d+), and combine the results. Then look at the places where you found them and look if there is a ']' following them.

我尝试了边界模式.

模式%f[%.%d]%d*%.?%d*%f[^%.%d%]]匹配所有十进制数字,后跟既不是数字也不是点的东西(或没有任何东西),然后是既不是]也不是数字也不是点的东西(或没有东西).不过,它也与单个点匹配.

The pattern %f[%.%d]%d*%.?%d*%f[^%.%d%]] matches all decimal numbers which are preceded by something that is neither digit nor dot (or by nothing), and followed by something that is neither ] nor digit nor dot (or by nothing). It also matches the single dot, though.

这篇关于如何在Lua中编写此正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆