正则表达式 - 匹配(不一定是连续的)顺序中的任何n个字符?

问题描述 投票:0回答:2

请考虑以下字符串:3ccc-8ab9-6335-b7af

我试图找出一个匹配的正则表达式,如果任何6个字符在它们的正确位置,但不一定是连续的。例如,以下每个都被视为匹配:

  • 3ccc-8cn4-o8cy-5234
  • 3ccc8ab9-6335-b7af
  • x9kf-k32p-6335-3l10
  • 3c08-a0m3-fd35-4g17

对不起,我真的很陌生,这超出了我的专业领域。我已经尝试过的东西甚至都不是很接近而且非常业余,我相信它们无法帮助我。

Applescript是首选。我之前只做了几个小脚本项目,以自动化与实验室数据相关的某些过程。

提前致谢。

regex applescript
2个回答
0
投票

这不是正则表达式的工作。

要在2个位置匹配123,您可以选择:

12-
1-3
-23

这可以用第一个位置的匹配来表示,然后匹配以下位置之一(1(2.)|(.3))或忽略第一个位置,但匹配最后两个位置:.23,所以整个表达式是“(1(2.)|(.3))|.23”。这种情况迅速失控:

1234 match at 2 pos

12..
1.3.
1..4
.23.
.2.4
..34

当然,你可以编写一个程序来生成这样的表达式,但是没有正则表达式的替代方法就这么简单了。比较字符串,char by char,count,size> = 6,完成?易于编写,易于理解。这里,3中2个匹配位置的简单情况已经离开了琐碎的空间。


0
投票

你的基本算法:

to isMatch(theText, thePattern, requiredCount)
    -- (this assumes both strings are equal length)
    set foundCount to 0
    repeat with i from 1 to length of thePattern
        if character i of theText equals character i of thePattern then
            set foundCount to foundCount + 1
            if foundCount = requiredCount then return true
        end if
    end repeat
    return false
end isMatch


set theList to {¬
    "3ccc-ocn4-o8cy-5234", ¬
    "o8cy-5234-3ccc-ocn4", ¬
    "3ccc&8ab9-6335-b7af", ¬
    "39kf-k32p-6335-3l10", ¬
    "3c08-a0m3-fd35-4g17", ¬
    "3ccc-xxxx?xxxx?xxxx", ¬
    "3ccc-xxxx?xxxx-xxxx"}

set thePattern to "3ccc-8ab9-6335-b7af"

set foundItems to {}
repeat with textRef in theList
    set theText to contents of textRef
    if isMatch(theText, thePattern, 6) then
        set end of foundItems to theText
    end if
end repeat
return foundItems

结果:

{"3ccc-ocn4-o8cy-5234", 
 "3ccc&8ab9-6335-b7af", 
 "39kf-k32p-6335-3l10", 
 "3c08-a0m3-fd35-4g17", 
 "3ccc-xxxx?xxxx-xxxx"}
© www.soinside.com 2019 - 2024. All rights reserved.