字符串匹配函数

本文关键字:函数 串匹配 字符串 字符 | 更新日期: 2023-09-27 17:58:13

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

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也许是解决方案,但我如何实现它?

谢谢Wes

字符串匹配函数

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

  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).*
    

不确定你在问什么,但

如果你有

List<string> strings = ...

string input = ...

然后你可以做

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

对于其他两个应该是相似的,在非运算符(!)中混合