Click here to Skip to main content
15,885,309 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I need to recognize two strings alongside the word 'or' from these examples:

Richard or James?
Car or Van?
Tree or Plant?

I need to recognize the two words alongside the 'or' word in each sentence, such that I have:

Car
Van

Richard
James

As a list or array, should I use Regex?
Posted

String.Split[^] can do it for you easily...
C#
string szSource = "Car or Van";
string[] szSep = new string[] {" or "};
string[] szRes;

szRes = szSource.Split(szSep, StringSplitOptions.None);
 
Share this answer
 
A regex may appear simple, but often its overkill

If you are always going to have <name1>space<'or'>space<name2>, then regex is overkill - you could use string.split and the ' ' (space) as the character to split on and pick out elements 0, 2 from the resultant array from the Split

If on the other hand, the names can have spaces in them (for example), or the requirements start getting more involved, then indeed, a regex may be the answer

I'd suggest
a) do it simply (String.Split)
b) test the simple way against all of your data
c) if that works, stay simple
d) if not, or requirements may change later, look at regex
 
Share this answer
 
v2
Try Split with Regex:
C#
using System;
using System.Text.RegularExpressions;

public class Program
{
    public static void Main()
    {
        string str = "Richard or James?";
        string[] w = Regex.Split(str, @"\s+or\s+|\?");
        foreach (string s in w)
        {
            Console.WriteLine(s);
        }
    }
}

Read more: http://www.dotnetperls.com/regex-split[^]
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900