C#,检查字符串,如果'a letter'后跟'a letter'

时间:2013-10-24 17:51:36

标签: c# string c#-4.0

让我们说,*必须跟着&amp ;. 例如,

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

4 个答案:

答案 0 :(得分:5)

通过查找任何星号(*)后面没有&符号(&)来查找失败:

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

答案 1 :(得分:2)

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

我会查找*之后没有的任何&。正则表达式应如下所示:(\*[^&])|(\*$)

简单的测试代码:

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

答案 2 :(得分:1)

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

/// 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;
}

答案 3 :(得分:0)

使用正则表达式并检查*&的匹配数量与* s

的数量相同

我头顶的代码,可能无法编译但是尝试:

Regex r = new Regex(@"\*&");
Regex r2 = new Regex(@"\*");
if (r.Matches(myString).Count == r2.Matches(myString).Count) //success!
相关问题