缺少后视的解决方法? [英] Workaround for the lack of lookbehind?

查看:22
本文介绍了缺少后视的解决方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了回答另一个用户的问题,我拼凑了以下正则表达式以匹配字符串中的数字.

To answer another user's question I knocked together the below regular expression to match numbers within a string.

\b[+-]?[0-9]+(\.[0-9]+)?\b

在提供我的答案后,我注意到在由于 \b 匹配句点字符而导致其中包含多个句点的数字序列的情况下,我得到了不需要的匹配.例如 "2.3.4" 将返回匹配 "2.3""4".

After providing my answer I noticed that I was getting unwanted matches in cases where there was a sequence of digits with more than one period among them due to \b matching the period character. For example "2.3.4" would return matches "2.3" and "4".

一个负面的前瞻和后视可以在这里帮助我,给我一个这样的正则表达式:

A negative lookahead and lookbehind could help me here, giving me a regex like this:

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

...除了由于某些未知原因,VBScript Regex(以及扩展名 VBA)不支持后视.

...except that for some unknown reason VBScript Regex (and by extension VBA) doesn't support lookbehind.

是否有一些解决方法可以让我确认匹配开头的单词边界不是句点而不将其包含在匹配中?

Is there some workaround that allows me to affirm that the word boundary at the start of the match is not a period without including it in the match?

推荐答案

也许你不需要回头看看.如果您能够提取特定的捕获组而不是整个匹配,那么您可以使用:

Perhaps you don't need a look behind. If you are able to extract specific capture groups instead of the entire match then you can use:

(?:[^.]|^)\b([+-]?([0-9]+(\.[0-9]+)))\b(?!\.)

将匹配:

2.5      
54.5
+3.45
-0.5

不匹配:

1.2.3
3.6.
.3.5

  • 捕获组 1 将输出整数和符号
  • 捕获组 2 将输出整数
  • 捕获组 3 将输出分数(如原始表达式中的捕获组 1)
  • 这篇关于缺少后视的解决方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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