C#,如果“一个字母”后跟“一个字母”,请检查字符串

本文关键字:一个字母 一个 检查 字符串 如果 后跟 | 更新日期: 2023-09-27 18:36:42

假设,* 后面必须跟着 &.例如

string asd = "Mother*&Mother*&Son";
// which is "Mother+ "*&" + "Mother" + "*&" + "Son"
// This is correct string.

不好的例子,

string asd = "Mother*Mother*&Son";
string asf = "Mother**&Mother*&Son";
string asg = "Mother*&*Mother*&Son";

如何在 C# 中检查字符串是否正确?

编辑
根据你们介绍的正则表达式的用法,我有一个侧面问题。我实际上使用逗号(,)而不是星号(*)和引号(")而不是&(&)。在 C# 中,(让我使用一个人的例子)

Regex.IsMatch("Mother,'",Mother,'"Son", @"',(?!")") 
//won't work.. any idea? 

我也试过

Regex.IsMatch("Mother,'",Mother,'"Son", @"',(?!'")") 
//not work, neither

C#,如果“一个字母”后跟“一个字母”,请检查字符串

通过查找任何不后跟与号 ( & 的星号 ( *) 来查找失败:

Regex.IsMatch("Mother*&*Mother*&Son", @"'*(?!&)")

您可以使用正则表达式。但是当字符串不正确时会更容易找到,然后只是否定结果。

我会寻找任何没有&*.正则表达式应如下所示:('*[^&])|('*$)

简单的测试代码:

var inputs = new[] {
    "Mother*&Mother*&Son",
    "Mother*Mother*&Son",
    "Mother**&Mother*&Son",
    "Mother*&*Mother*&Son",
    "Mother*&Mother*&Son*"
};
var regex = new Regex(@"('*[^&])|('*$)");
var isOK = inputs.Select(x => !regex.IsMatch(x)).ToList();

返回结果列表,其中包含 truefalsefalsefalsefalse

对于这样的事情,我倾向于直接方法,而不是使用正则表达式。这将使最多一次遍历整个字符串,这应该比正则表达式更有效。

/// Return true if every instance of 'a' in the string is followed by 'b'. 
/// Also returns true if there are no instances of 'a' in the string.
/// Returns false if there exists any 'a' that is not followed by 'b'.
public static bool IsTwoCharSequence(string s, char a, char b)
{
    if(String.IsNullOrEmpty(s)) return true;
    if(s[s.Length - 1] == a) return false; // ends in a, not followed by b. Condition failed.
    int index = s.IndexOf(a); // find the first a
    while(index != -1)
    {
        if(s[index + 1] != b) return false; // a not followed by b.
        index = s.IndexOf(a, index + 1);
    }
    return true; // either no a, or all a followed by b.
}

编辑:此外,您无需担心如何引用分隔符字符,因为它们也是正则表达式中的特殊字符。


编辑2:是的,这是两个循环,但看看每个循环在做什么。

内部循环(String.IndexOf 内部循环)将循环访问字符,直到找到传入的字符。对 IndexOf 的第一次调用(while 循环之外的调用)从字符串的开头开始搜索,后续调用从该索引开始,并继续搜索到下一个匹配项或结束。总的来说,我们只对整个字符串进行了一次传递。

这是另一种方法,它在概念上与上述方法相似,但"仅迭代整个字符串一次"更为明确。

public static bool IsTwoCharSequence(string s, char a, char b)
{
    if (String.IsNullOrEmpty(s)) return true;
    bool foundA = false;
    foreach (char c in s)
    {
        if (foundA && c == b)
            foundA = false;
        else if (foundA)
            return false;
        else if (c == a)
            foundA = true;
    }
    if (foundA) return false; // 'a' was the last char in the string.
    return true;
}

使用正则表达式并检查 *& 的匹配数是否与 *s 的匹配数相同

我头顶的代码,可能不会编译,但尝试:

Regex r = new Regex(@"'*&");
Regex r2 = new Regex(@"'*");
if (r.Matches(myString).Count == r2.Matches(myString).Count) //success!