检索由字符串'或'分隔的两个字符串? [英] Retrieving two strings that are separated by the string 'or'?

查看:109
本文介绍了检索由字符串'或'分隔的两个字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要识别两个字符串以及这些例子中的'或'一词:



Richard或James?

Car or Van ?

树木或植物?



我需要识别每个句子中或字旁边的两个单词,这样我才有:





Van



Richard

James



作为列表或数组,我应该使用正则表达式吗?

解决方案

String.Split [ ^ ]可以做它很适合你...

  string  szSource =    Car or Van; 
string [] szSep = new string [] { };
string [] szRes;

szRes = szSource.Split(szSep,StringSplitOptions.None);


正则表达式可能看似简单,但通常是过度杀伤



如果你总是要< name1>空格<'或'>空格< name2>,那么正则表达式就是矫枉过正 - 你可以使用string.split和''(空格)作为要分割的字符,从分裂中从结果数组中挑出元素0,2



如果另一方面,名称可以在它们中有空格(例如),或者要求开始越来越多,然后确实,正则表达式可能就是答案



我建议

a)简单地做(String.Split)

b)测试你所有数据的简单方法

c)如果有效,保持简单

d)如果没有,或者要求可能会在以后更改,请查看正则表达式


尝试使用正则表达式进行拆分:

 使用系统; 
使用 System.Text.RegularExpressions;

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



了解更多: http://www.dotnetperls.com/regex-split [ ^ ]


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?

解决方案

String.Split[^] can do it for you easily...

string szSource = "Car or Van";
string[] szSep = new string[] {" or "};
string[] szRes;

szRes = szSource.Split(szSep, StringSplitOptions.None);


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


Try Split with Regex:

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[^]


这篇关于检索由字符串'或'分隔的两个字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆