简体   繁体   English

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

[英]C#, check string if 'a letter' is followed by 'a letter'

Let say, * has to be followed by &. 比方说,*必须跟着&。 For example, 例如,

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

Bad example, 不好的例子,

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

How can I check if the string is correct or not in C#? 如何在C#中检查字符串是否正确?

EDIT 编辑
based on the usage of Regex that you guys introduced, I have a side question. 根据你们介绍的正则表达式的用法,我有一个附带问题。 I am actually using comma(,) instead of asterisk(*) and quotation mark(") instead of ampersand(&). In C#, (Let me use one of the guy's example) 我实际上使用逗号(,)而不是星号(*)和引号(“)代替&符号(&)。在C#中,(让我使用其中一个人的例子)

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

I also tried 我也试过了

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

查找故障通过寻找任何星号( * )后面没有符号( & ):

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

You can use regex. 你可以使用正则表达式。 But it will be easier to find when string is not correct and then just negate the result. 但是当字符串不正确时会更容易找到,然后只是否定结果。

I would look for any * which is not followed by & . 我会寻找任何*后面没有& The regex should look like: (\\*[^&])|(\\*$) 正则表达式应如下所示: (\\*[^&])|(\\*$)

Simple test code: 简单的测试代码:

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();

Returns a list of results, which contains true , false , false , false , false . 返回结果列表,其中包含truefalsefalsefalsefalse

For something like this, I'd favor the direct approach, rather than using Regex. 对于这样的事情,我倾向于采用直接方法,而不是使用正则表达式。 This will make at most one pass through the entire string, which should be more efficient than a 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.
}

Edit: In addition, you don't need to worry about how to quote your separator characters, when they're also special characters within a Regex. 编辑:此外,当它们也是正则表达式中的特殊字符时,您不必担心如何引用分隔符。


Edit 2: Yes, it's two loops, but look at what each loop is doing. 编辑2:是的,它是两个循环,但看看每个循环正在做什么。

The inner loop, the one inside of String.IndexOf, will iterate through characters until it finds the passed-in character. 内部循环(String.IndexOf中的内部循环)将遍历字符,直到找到传入的字符。 The first call to IndexOf (the one outside the while loop) starts searching at the beginning of the string, and the subsequent ones start at that index, and continue searching to the next match, or to the end. 第一次调用IndexOf(while循环之外的那个)开始在字符串的开头搜索,后续的调用从该索引开始,继续搜索下一个匹配或结束。 Overall, we've made just one pass over the entire string. 总的来说,我们只对整个字符串进行了一次传递。

Here's another method, which is similar in concept to the above one, but where the 'iterate the entire string only once' is more explicit. 这是另一种方法,它在概念上类似于上面的方法,但是'只迭代整个字符串一次'更明确。

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

Use Regular expressions and check that the number of matches for *& is the same as the number of *s 使用正则表达式并检查*&的匹配数是否与* s的数量相同

code of the top of my head, may not compile but try: 我头顶的代码,可能无法编译但尝试:

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

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

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