使用任何程序在字符串中查找特定模式(序列)

时间:2013-01-15 11:55:09

标签: regex string search match

我需要任何方式(使用任何免费程序)在字符串中查找模式。

例如:

我搜索12321

字符串为dkaowkdlertrelkjh

searchstring有一个特定的模式(第一个和最后一个字符是相同的,第二个和第四个是相同的,第三个是与所有其他字符不同)

在字符串中,它由部分ertre dkaowkdl**ertre**lkjh匹配,因为它遵循相同的模式。

关于如何做到这一点的任何想法?

1 个答案:

答案 0 :(得分:2)

你可以自己写。这并不难,我们所要做的就是找到如何匹配重复组。我是一个python程序员,所以我的解决方案是 python

re module的帮助下,我们发现我们可以将匹配的组命名为(?P<name>...),然后像(?P=name)一样对其进行处理。

就是这样。 我们将使用模式描述符字母模式(而不是数字) - 它有点简单,并且使我们能够在内存中存储更多的组。

import re

def GenerateRegexp(patternDescription, anySequence='.+'):
  '''
  Creates string regexp, that will describe our ABCAB-pattern in terms of regexp
  '''
  used = []
  regexp = ""
  for character in patternDescription:
     if character not in used:
        regexp += "(?P<%s>%s)" % (character, anySequence)  # we should be more attentive here if we expect % here, we can use str.format instead, but still might have a problem with {} symbols
        used.append(character)
     else:
        regexp += "(?P=%s)" % character
  return regexp

def Matches(string, pattern):
    '''
    Returns a bool answer, wheter string matches our pattern
    '''
    r = generate_regexp(pattern)
    SearchPattern = re.compile(r)
    return bool(SearchPattern.match(string))

使用示例(检查,aabbaabb字符串是否与'abab'模板匹配(使用您的语言为1212)):

print Matches (patternDescription="abab", string="aabbaabb")