正则表达式用于查找子字符串

时间:2010-02-26 22:23:38

标签: regex

正则表达式是正确的解决方法吗?

我有一个字符串列表(大猿,大鸟,小鸟,小猿,中猿,银猿,蓝猿,黑猿)如果我输入'大'正则表达式应该返回(大猿,大Bird),如果我输入'al',返回的列表是'Small Bird,Small Ape)。这是可能的,使用正则表达式进行上下文搜索吗?

4 个答案:

答案 0 :(得分:0)

正则表达式可以为你做到,是的。根据您使用的.Contains("Big")或类似的编程语言,这可能是一种更直接的方法。

答案 1 :(得分:0)

是的,正则表达式可以判断字符串是否与模式匹配,例如:

'大猿'匹配/大/? =>是 '小猿'匹配/大/? =>没有 '大猿'匹配/ al /? =>没有 '小猿'匹配/ al /? =>是

几乎所有语言都可以让你轻松使用正则表达式,所以你可以这样做。

但正则表达式在处理更复杂的模式时非常有用。在您的情况下,您的编程语言可能会为您的问题提供更简单的功能。例如,在php中:

'大猿'匹配/大/?翻译为(strpos ('Big Ape', 'Big') !== false)

答案 2 :(得分:0)

这很简单,但RE比简单的子串匹配更强大。

这是python中的一个例子

import re   ### regular expression library

possibilities = ['Big Ape', 'Big Bird', 'Small Bird', 'Small Ape',
                 'Medium Ape', 'Silver Ape', 'Blue Ape', 'Black Ape']

def search(list, pattern):
    output = []
    for item in list:
       match = re.search(pattern, item)
       if match:
           output.append(item)
    return output

输出:

>>> search(possibilities, 'Big')
['Big Ape', 'Big Bird']

>>> search(possibilities, 'al')
['Small Bird', 'Small Ape']

答案 3 :(得分:0)

是的,正则表达式是一种很好的方法。

这是C#中的一个示例控制台应用程序,它将您想要匹配的内容作为参数;例如问题中的'大'或'al'。在内部,该参数用作正则表达式以匹配您的样本输入。

代码

  static void Main(string[] args)
  {
        // Inputs to try to match.
        string[] inputs = { "Big Ape", "Big Bird", "Small Bird", "Small Ape",
                            "Medium Ape", "Silver Ape", "Blue Ape", "Black Ape" };

        var stringToMatch = args[0];
        Regex regex = new Regex(stringToMatch, RegexOptions.IgnoreCase);

        // Container for all inputs that match the given regular expression.
        var matchList = new List<string>();
        foreach (var input in inputs)
        {
            Match parse = regex.Match(input);
            if (parse.Success)
            {
                matchList.Add(input);
                Console.WriteLine(input);
            }
        }
  }

输出

  

SampleApplication.exe al   小鸟
  小猿

     

SampleApplication.exe大
  大猿
  大鸟

相关问题