字符串匹配功能

时间:2011-06-03 00:28:52

标签: c# .net regex string .net-4.0

您好   我喜欢构建一个字符串函数:

if member of a list of string: 
    "Nissan" from "Honda, Toyota, Nissan, Mazda"

  if start with or end with
    "Nissan" from "Nis*" as start with 
    "Nissan" from "*san" as end with

  if not start with or end with 
    "Ford" from "^Nis*" as start with 
    "Ford" from "^*san" as end with 

  if Not member of a list of string:
    "Ford" from "^Hon*, ^Toy*, Nis*, Mazda"

我认为Regex可能是解决方案,但我是如何实现的?

谢谢 韦斯

2 个答案:

答案 0 :(得分:2)

很难理解你的要求,但我会尽力猜测:

  1. 检查字符串是否为以下之一:Honda, Toyota, Nissan, Mazda

    ^(Honda|Toyota|Nissan|Mazda)$

  2. Nis

    开头
    ^Nis.*$
    
  3. san

    结束
    ^.*san$
    
  4. 不以Nis

    开头
    ^(?!Nis).*
    
  5. 不以san

    结尾
    ^.*(?<!san)$
    
  6. 不包含任何Hon*, Toy*, Nis*, Mazda

    ^(?!Hon.*|Toy.*|Nis.*|Mazda).*
    

答案 1 :(得分:1)

不完全确定你在问什么,但是

如果你有

List<string> strings = ...

string input = ...

然后你可以做

bool memberIsInList = strings.Contains(input);      
bool memberStartsOrEndsWith = strins.Any(s => s.StartsWith(input) || s.EndsWith(input));

对于其他两个应该是相似的,在not运算符(!

中混合