开发者

Regular Expression for finding sub string

Is a regular expression the correct way of going about this?

I have a list of strings (Big Ape, Big Bird, Small Bird, Small Ape, Medium Ape, Silver Ape, Blue Ape, Black Ape) if I enter 'Big' the regular expression should return (Big Ape, Big Bird), if I enter 'al' the the list that is returned is 'Small Bird, Small Ape). Is this pos开发者_C百科sible, kind of context search with regular expressions?


This is easy, but RE's are more powerful than you need for simple substring matching.

Here is an example in 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

The output:

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

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


A regex could do that for you, yes. Depending on the programming language you are using a .Contains("Big") or something like that might be a more straightforward approach.


yes it is possible, regular expression can tell if a string match or not a pattern, eg:

does 'Big Ape' match /Big/ ? => yes does 'Small Ape' match /Big/ ? => no does 'Big Ape' match /al/ ? => no does 'Small Ape' match /al/ ? => yes

almost any language let you use regular expression easily so you can probably do this.

but regular expressions are really usefull when working with more complexe pattern. In your case, your programmation language may provide simpler function for your problem. eg, in php:

does 'Big Ape' match /Big/ ? translate to (strpos ('Big Ape', 'Big') !== false)


Yes, a regular expression is a great way to do this.

Here's a sample console application in C# that takes what you'd like to match as an argument; for example 'big' or 'al' as in the question. Internally, the argument is used as a regex to match against your sample inputs.

Code

  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);
            }
        }
  }

Output

SampleApplication.exe al
Small Bird
Small Ape

SampleApplication.exe big
Big Ape
Big Bird

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜