C# 仅使用字母,否则返回true
好的,我需要测试一个变量是否包含字母以外的任何内容;这意味着不允许使用空格、数字和符号。我想我已经弄明白了,但是我不能让正则表达式工作。以下是我所拥有的:C# 仅使用字母,否则返回true,c#,C#,好的,我需要测试一个变量是否包含字母以外的任何内容;这意味着不允许使用空格、数字和符号。我想我已经弄明白了,但是我不能让正则表达式工作。以下是我所拥有的: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace soro { class Prog
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace soro
{
class Program
{
static void notOnlyString(string word)
{
Regex.IsMatch(word, @"^[a-zA-Z]+$");
}
static void Main(string[] args)
{
string var1;
//lots of code here
var1 = Console.ReadLine();
if (notOnlyString(var1))
{
//do this if it has a number, space or symbol; anything but
//letters
}
//more code
}
}
您可以使用
bool result = word.All(Char.IsLetter);
如果你需要,就用它
bool result = word.All(Char.IsLetterOrDigit);
您应该将正则表达式语法更改为: ^[a-zA-Z]*$ 一个很好的在线工具是 希望这有帮助,
Serge你的正则表达式看起来很正确。代码的一大错误是返回类型为
notOnlyString
顺便说一句,notOnlyString
的命名不正确。请不要使用“否定”语句作为方法名。我建议IsOnlyLetters
由于要在if语句中调用IsOnlyLetters
,因此应该返回bool
值
static bool notOnlyString(string word) // note that I changed "void" to "bool"
{
return Regex.IsMatch(word, @"^[a-zA-Z]+$"); / here I added "return" to return the result of the "IsMatch" call.
}
现在,您应该将if语句中的条件更改为
(!IsOnlyLetters(var1))
,一切都应该正常。那么您对变量类型(如布尔值)和返回值了解多少呢?看起来你需要一本好的C语言书或教程。编译器会告诉你问题出在哪里。阅读错误消息。regex不是问题所在,是方法的签名notOnlyString
导致了问题。它的返回类型为void,这意味着它不应该返回任何内容。您想要的是返回一个布尔值。这似乎是可行的,尽管它是新的,但它表明并非所有代码路径都返回一个值,而且我不太确定它的含义-------------------------------------------------------静态bool onlyString(string word){bool result=word.all(Char.isleter);}也是堆栈交换的新手您应该返回result,static bool onlyString(string word){bool result=word.All(Char.isleter);return result;}为什么?您的示例中唯一的区别是0-n个字母的匹配,而他匹配1-n个字母。但是这没有任何区别,因为整个字符串都是匹配的。