从字符串中提取最大的数字序列(正则表达式,还是?) [英] Extract largest numeric sequence from string (regex, or?)

查看:36
本文介绍了从字符串中提取最大的数字序列(正则表达式,还是?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有类似于以下的字符串:

 4123499-TESCO45-123每99999994_54

而我想分别提取每个字符串中最大的数字序列:

 412349999999994

我以前尝试过正则表达式(我使用的是 VB6)

 设置 rx = New RegExprx.Pattern = "[^\d]"rx.Global = 真StringText = rx.Replace(StringText, "")

这让我走到了一半,但它只删除了非数字值,我最终得到了第一个字符串:

412349945123

我能找到一个能满足我要求的正则表达式,还是我必须尝试另一种方法?本质上,我的模式必须是任何不是最长数字序列的东西.但我实际上不确定这是否是一个合理的模式.任何对正则表达式有更好处理能力的人都可以告诉我我是否会陷入困境?感谢您的帮助!

解决方案

您无法仅通过正则表达式获得结果.您必须提取所有数字块并使用其他编程方法获得最长的块.

这是一个例子:

Dim strPattern As String: strPattern = "\d+"Dim str As String: str = "4123499-TESCO45-123"Dim regEx 作为新的 RegExpDim 匹配 As MatchCollection暗匹配作为匹配将结果调暗为字符串使用正则表达式.Global = 真.MultiLine = 假.IgnoreCase = False.Pattern = strPattern结束于设置匹配 = regEx.Execute(str)对于每米匹配如果结果<Len(m.Value) 然后结果 = m.Value下一个调试.打印结果

带有 RegExp.Global=True\d+ 将查找所有数字块,然后在循环处理所有匹配项后仅打印最长的块.>

I have strings similar to the following:

 4123499-TESCO45-123
 every99999994_54

And I want to extract the largest numeric sequence in each string, respectively:

 4123499
 99999994

I have previously tried regex (I am using VB6)

 Set rx = New RegExp
 rx.Pattern = "[^\d]"
 rx.Global = True

 StringText = rx.Replace(StringText, "")

Which gets me partway there, but it only removes the non-numeric values, and I end up with the first string looking like:

412349945123

Can I find a regex that will give me what I require, or will I have to try another method? Essentially, my pattern would have to be anything that isn't the longest numeric sequence. But I'm not actually sure if that is even a reasonable pattern. Could anyone with a better handle of regex tell me if I am going down a rabbit hole? I appreciate any help!

解决方案

You cannot get the result by just a regex. You will have to extract all numeric chunks and get the longest one using other programming means.

Here is an example:

Dim strPattern As String: strPattern = "\d+"
Dim str As String: str = "4123499-TESCO45-123"
Dim regEx As New RegExp
Dim matches  As MatchCollection
Dim match As Match
Dim result As String

With regEx
     .Global = True
     .MultiLine = False
     .IgnoreCase = False
     .Pattern = strPattern
End With

Set matches = regEx.Execute(str)
For Each m In matches
  If result < Len(m.Value) Then result = m.Value
Next

Debug.Print result

The \d+ with RegExp.Global=True will find all digit chunks and then only the longest will be printed after all matches are processed in a loop.

这篇关于从字符串中提取最大的数字序列(正则表达式,还是?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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