简体   繁体   English

查找所有字符都用+括起来

[英]Find all char are enclosed with +

I have long string , now I need to find that in string each char (not digit) are enclosed with + sign. 我有长字符串,现在我需要在字符串中找到每个字符(不是数字)都用+符号括起来。

For example 例如

  • 1q+1q+1 : result- false 1q + 1q + 1:结果 - 错误
  • 1+q+1+q+1 : result- true 1 + q + 1 + q + 1:结果为真
  • q+a+123 : result - false q + a + 123:结果 - 错误

As you can see each char must with surrounded by +, to be true. 正如你所看到的,每个char必须用+包围,才是真的。

Note : Need to check only char between [a-zA-Z] . 注意 :需要仅检查[a-zA-Z]之间的字符。 If there is no any alphabet in string then it should return true. 如果字符串中没有任何字母,那么它应该返回true。 (eg : 1+1+1 or 1++.25,+5 will return true) (例如:1 + 1 + 1或1 ++。25,+ 5将返回true)

I'm trying to do with regex. 我正在尝试使用正则表达式。 but it's not working. 但它不起作用。

public static bool IsValidPattern(string str)
  {
     return Regex.IsMatch(str, @"\?\+[a-zA-Z]\+$");
  }

.NetFiddle .NetFiddle

Go the other way round and check if there is a char which is not enclosed in + with negative look ahead and look behind: 反之亦然,检查是否有一个未包含在+的字符,前面有负向并且向后看:

public static bool IsValidPattern(string str)
  {
     return !Regex.IsMatch(str, @"((?<!\+)[a-zA-Z])|([a-zA-Z]+(?!\+))");
  }

Fiddle here 在这里小提琴

Short explanation: 简短说明:

| : is an or so matching against ((?<!\\+)[a-zA-Z]) or ([a-zA-Z](?!\\+)) :是((?<!\\+)[a-zA-Z])([a-zA-Z](?!\\+))左右匹配

((?<!\\+) is a negative lookbehind which assures that the following ( [a-zA-Z] ) is not preceded by a \\+ ((?<!\\+)是一个负面的外观,它确保以下( [a-zA-Z] )前面没有\\+

((?!\\+) is a negative lookahead which assures that the preceding ( [a-zA-Z] ) is not followed by \\+ ((?!\\+)是一个负前瞻,它确保前面的( [a-zA-Z] )后面没有\\+

So the first alternative is matching strings like 'a+', 'c+' and so on and the second one the other way round ( '+a', '+c' ) which is considered invalid. 因此,第一种方法是匹配字符串,如'a+', 'c+'等,而第二种方式则是另一种方式( '+a', '+c' ),这被认为是无效的。

Regexes have the advantege of being concise but can become quite cryptic and less maintainable at the same time. 正则表达式具有简洁的优点,但同时可能变得非常神秘且难以维护。

Is there any reason why you don't want your code to clearly express what it's doing and to be able to add any other conditions in the future? 你有什么理由不希望你的代码清楚地表达它正在做什么,以及能够在将来添加任何其他条件吗?

public static bool IsValidPattern(string str)
{
    for (int i = 0; i < str.Length; i++)
    {
        if (char.IsLetter(str[i]))
        {
            if (i == 0 || i == str.Length - 1 || str[i - 1] != '+' || str[i + 1] != '+')
            {
                return false;
            }
        }
    }

    return true;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM