检查一个字符串是否只包含'&'字符

Check whether a string contain '&' character only

如何检查一个字符串是否只包含“&”。我的意思是,如果用户将输入 & 或 &&& 或一串“&”。请注意 http://myurl.com/&var=79 或类似的东西应该被忽略。它应该检查那些包含 & 字符的字符串。请帮帮我!!!

你可以这样试试:

string str;
Regex r = new Regex ("&");
bool b = r.IsMatch (str);

或使用 LINQ

new[] { "&" }.All(c => s.Contains(c))

或者试试这个:

if (str.Except("&").Any())
{
    //code
}

当你说

string contains "&" only

我假设,带有任何其他字符的字符串都是无效的。

string str = "&&&";
bool result = str.All(x => x == '&'); //true, because it contains no other char

另一种方式 - 没有 linq 的 oneliner

bool result = str.Replace("&", String.Empty).Length == 0;

我确信正则表达式有更好的方法,但这里有一个可能的解决方案:

class Program
    {
        static void Main(string[] args)
        {
            char testChar = '&';
            string test1 = "&";
            string test2 = "&&&&&&&&&&";
            string test3 = "&&&&&&&u&&&&&&&";

            Console.WriteLine(checkIfOnly(testChar, test1)); // true
            Console.WriteLine(checkIfOnly(testChar, test2)); // true
            Console.WriteLine(checkIfOnly(testChar, test3)); // false
            Console.WriteLine(checkIfOnly('u', test3));      // false
            Console.WriteLine(checkIfOnly('u', "u"));      // true
            Console.WriteLine(checkIfOnly('u', "uuuu"));      // true


        }

        static bool checkIfOnly(char testChar, string s)
        {
            foreach (char c in s)
            {
                if (c != testChar) return false;
            }
            return true;
        }

    }
  string s = "&&& &&&";

  if (s.Contains("&"))
  {
     //do your work
  }

正则表达式解决方案

string str = "&&&&"; 
bool b = Regex.IsMatch(str,"^&+$");

问题有点不清楚,但假设这个想法是测试字符串是否仅由 & 字符组成,这里还有一种检查方法:

bool containsOnlyAmps = false;
string testString = "&";

containsOnlyAmps = 
    !string.IsNullOrEmpty(testString) 
    && testString == new string('&', testString.Length);

首先检查我们是否有一个非空、非空的字符串。然后它使用 string 构造函数的 string.String(char c, int count) 重载。它生成一个包含给定 char 重复计数次数的字符串。所以我们输入字符 &,重复 testString.Lenght 次,然后将结果与 testString 本身进行比较。

如果原始字符串有任何其他字符,则containsOnlyAmps将为假。否则为真。

这是一个相当简单的方法:

bool allAmpersands = !string.IsNullOrEmpty(str) && str.Trim('&').Length == 0;

如果字符串不为空,则在去掉两端的“&”后检查字符串中是否还有剩余。

这就是我使用正则表达式的方式。 ^&+$ 匹配仅包含字符“&”的整个字符串。我建议阅读正则表达式,它可能看起来很复杂,但在尝试解析或过滤字符串时会派上用场。

string invalid = "ccc&cc";
string valid = "&&";

if(Regex.IsMatch(invalid, "^&+$"))
    Console.WriteLine("Does not execute");

if(Regex.IsMatch(valid, "^&+$"))
    Console.WriteLine("Will execute");

这是检查是否有任何字符串具有 & 符号的简单方法:

internal class Program
{
    private static void Main(string[] args)
    {
        bool ans = HasAmpersandSign("some&word");
        Console.WriteLine(ans);
    }

    private static bool HasAmpersandSign(string s)
    {
        return s.Contains("&");
    }
}

但是,如果您想检查字符串是否只有一个与符号,则间接暗示该字符串的长度只需要一个字符。

internal class Program
    {
        private static void Main(string[] args)
        {
            string s = "&someword";

            bool ans = HasAmpersandSign("some&word");

            Console.WriteLine(ans);

            Console.WriteLine(HasAmpersandSignOnly(s));
        }

        private static bool HasAmpersandSign(string s)
        {
            return s.Contains("&");
        }

        private static bool HasAmpersandSignOnly(string s)
        {
            return s.Contains("&") && s.Length == 1;
        }
    }

如果你想 validate/check 一个字符串只包含和号(& 符号)字符

您可以从 System.Text.RegularExpressions

Regex class

检查下面的代码示例。你可以执行它here

string test1 = "&";
string test2 = "&&&&&&&&&&";
string test3 = "&&&&&&&u&&&&&&&";
var test4 = "foo&";
var regex = new Regex("^[&]+$");

Console.WriteLine(regex.IsMatch(test1));
Console.WriteLine(regex.IsMatch(test2));
Console.WriteLine(regex.IsMatch(test3));
Console.WriteLine(regex.IsMatch(test4));

正则表达式 [&]+ 检查一次或多次出现的 & 符号

尝试以下代码

    public static void Main() 
    {
        Console.WriteLine(ValidateString("", '&')); //False
        Console.WriteLine(ValidateString("Foo&", '&')); //False
        Console.WriteLine(ValidateString("&Foo", '&')); //False
        Console.WriteLine(ValidateString("&&&", '&')); //True
        Console.WriteLine(ValidateString("&", '&')); //True
        Console.ReadLine();
    }

   static bool ValidateString(string str, char testChar) 
   {
     if (String.IsNullOrEmpty(str))
        return false;
     if (Regex.Matches(str, testChar.ToString()).Count == str.Length)
        return true;
     else
        return false;
   }
bool ContainsOnlyAmpersand(string str){ return str.?Length > 0 && !str.Any(c => c != '&'); }

Returns false 对于 null/empty 字符串。 这应该比其他答案更高效,因为 Any() 可以提前中止,而 All() 必须始终完全评估字符串。 Except('&') 方法创建了一个额外的迭代器,因此可能会更慢(尽管需要基准测试才能确定)。

使用正则表达式怎么样:

string strMatch = "Yeah& yeah yeah";
string strNoMatch = "Yeah &&yeah yeah";
Regex r = new Regex("^[^&]*&[^&]*");
r.IsMatch(strMatch);   // returns true
r.IsMatch(strNoMatch); // returns false

正则表达式分解:

^[^&]*  -- string beginning, match any number of occurrences of "not &"
&       -- match exactly one "&"
[^&]*   -- match the rest of the string

虽然晚了,希望对你有所帮助

using System;

public class Program
{
    public static void Main()
    {
        string url = "http://myurl.com/&&var=79";
        string[] parameters = url.Split('&');

        //Method 1 - just to check existance of "&" character
        if(parameters.Length > 0) Console.WriteLine("Character '&' present");

        //Method 2 - check if repeated occurence of "&" exists
        bool isRepetedExistance = false;
        foreach(string keyValuePair in parameters) {
            if(keyValuePair.Length == 0) {
                isRepetedExistance = true;
                break;
            }
        }
        Console.WriteLine(String.Format("Repeted existance of character '&' is {0}present", (isRepetedExistance ? "" : "not ")));
    }
}

像这样

static readonly Regex Validator = new Regex(@"^[&]+$");

public static bool IsValid(string str) {
    return Validator.IsMatch(str);
}

正则表达式是这样工作的:

^ matches the beginning of the string
[...] matches any of the characters that appear in the brackets
+ matches one or more characters that match the previous item
$ matches the end of the string

如果没有 ^ 和 $ 锚点,正则表达式将匹配任何包含至少一个有效字符的字符串,因为正则表达式可以匹配字符串的任何子字符串使用传递它。 ^ 和 $ 锚点强制它匹配整个字符串。

如果字符串包含与符号以外的任何内容,这将 return 为真。

如果字符串为空,OP 没有指定要做什么 - 在这种情况下,此代码将 return 为 false。

bool ContainsNonAmpersands=!Regex.IsMatch(str,"[^&]");

根据您希望多久执行一次此检查,我将使用 Regex 对象来检查字符串。通常,在文本中搜索模式时,正则表达式非常有用。这里^表示字符串的开头,$表示string/line.

的结尾
Regex re = new Regex("^&+$");

re.IsMatch("&&&&&");          // returns true
re.IsMatch("www.url.com/&2"); // returns false