tags:

views:

60

answers:

4

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 possible, kind of context search with regular expressions?

A: 

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.

Rune
The language is Real Basic and I'm pretty sure it doesn't have such powerful functions built in. I believe this would need to be a match with the specified reg ex pattern. It the pattern I need help with.
driveBy
A: 

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)

mathroc
A: 

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']
Joe Koberg
A: 

The regex in this case is simply your target string. Just compare it to all the items in the list. In C#, it'd be something like:

  static void Main(string[] args)
  {
     string[] itemArray = { "Big Ape", "Big Bird", "Small Bird", "Small Ape", "Medium Ape", "Silver Ape", "Blue Ape", "Black Ape" };

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

     IList<string> matchList = new List<string>();
     foreach (var item in itemArray)
     {
        Match parse = regex.Match(item);
        if (parse.Success)
        {
           matchList.Add(item);
           Console.WriteLine(item);
        }
     }
  }
Dave M