正则表达式(按顺序查找匹配的字符)

时间:2016-07-15 08:40:41

标签: python regex

我们假设我有以下字符串变量:

welcome = "StackExchange 2016"
string_to_find = "Sx2016"

在这里,我想使用正则表达式在string_to_find内找到字符串welcome。我想查看string_to_find中的每个字符是否与welcome中的字符顺序相同。

例如,此表达式将评估为True,因为'S'位于'x'两个字符串之前,'x'位于'2'之前,在'2'之前0,等等。

使用正则表达式有一种简单的方法吗?

4 个答案:

答案 0 :(得分:3)

你的答案相当微不足道。 .*字符组合匹配0个或更多字符。为了您的目的,您可以将它放在那里的所有角色之间。与S.*x.*2.*0.*1.*6中一样。如果匹配此模式,则字符串服从您的条件。

对于一般字符串,您可以在字符之间插入.*模式,同时处理转义特殊字符,如文字点,星号等,否则可能由正则表达式解释。

答案 1 :(得分:1)

使用与.匹配的通配符,并重复*

expression = 'S.*x.*2.*0.*1.*6'

您也可以使用join()汇总此表达式:

expression = '.*'.join('Sx2016')

或者只是在没有正则表达式的情况下找到它,检查string_to_find中每个welcome个字符的位置是否按升序进行,处理{{1}中的字符的情况通过捕获string_to_find

,{}}}中不存在1}}
welcome

答案 2 :(得分:0)

此功能可能符合您的需要

var chart = c3.generate({
            bindto:'#png-container',
            data: {
              json: [
                {name: 'name1', upload: 200, download: 200, total: 400},
                {name: 'name1', upload: 100, download: 300, total: 400},
                {name: 'name2', upload: 300, download: 200, total: 500},
                {name: 'name3', upload: 400, download: 100, total: 500},
              ],
              keys: {
                x: 'name', // it's possible to specify 'x' when category axis
                value: ['upload', 'download'],
              },
              groups: [
                ['name']
              ]
            },
            axis: {
              x: {
                type: 'category'
              }
            }
        });

import re def check_string(text, pattern): return re.match('.*'.join(pattern), text) 创建一个模式,其中所有字符均以'.*'.join(pattern)分隔。例如

'.*'

答案 3 :(得分:0)

实际上有一系列 chars ,如Sx2016,最适合您目的的模式更具体:

S[^x]*x[^2]*2[^0]*0[^1]*1[^6]*6

你可以获得这种定义这样一个函数的检查:

import re
def contains_sequence(text, seq):
    pattern = seq[0] + ''.join(map(lambda c: '[^' + c + ']*' + c, list(seq[1:])))
    return re.search(pattern, text)

这种方法增加了一层复杂性,但也带来了一些好处:

  1. 它是最快的一个,因为正则表达式引擎只沿着字符串向下走一次,而点星方法一直走到序列的末尾,每次.*都返回使用。比较相同的字符串(~1k字符):

  2. 它也适用于输入中的多行字符串。

  3. 示例代码

    >>> sequence = 'Sx2016'
    >>> inputs = ['StackExchange2015','StackExchange2016','Stack\nExchange\n2015','Stach\nExchange\n2016']
    >>> map(lambda x: x + ': yes' if contains_sequence(x,sequence) else x + ': no', inputs)
    ['StackExchange2015: no', 'StackExchange2016: yes', 'Stack\nExchange\n2015: no', 'Stach\nExchange\n2016: yes']