Lua中这个正则表达式怎么写? [英] How to write this regular expression in Lua?

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

问题描述

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

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

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

基本上,它匹配十进制格式的数字(例如:1、1.1、0.1、0.11),不以]"结尾,我一直在尝试使用 string 用 Lua 编写这样的正则表达式.gmatch,但我对 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.

我对 前沿模式进行了一些试验.

I experimented a bit with the frontier pattern.

模式 %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天全站免登陆