有没有在C#中的方法来检查一个字符串是否是一个有效的标识符 [英] Is there a method in C# to check if a string is a valid identifier
本文介绍了有没有在C#中的方法来检查一个字符串是否是一个有效的标识符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在Java中,有一个名为 isJavaIdentifierStart
和 isJavaIdentifierPart
的字符类方法可以用来判断是否一个字符串是一个有效的Java标识符,像这样:
In Java, there are methods called isJavaIdentifierStart
and isJavaIdentifierPart
on the Character class that may be used to tell if a string is a valid Java identifier, like so:
public boolean isJavaIdentifier(String s) {
int n = s.length();
if (n==0) return false;
if (!Character.isJavaIdentifierStart(s.charAt(0)))
return false;
for (int i = 1; i < n; i++)
if (!Character.isJavaIdentifierPart(s.charAt(i)))
return false;
return true;
}
有没有这样的事情对于C#?
Is there something like this for C#?
推荐答案
基本上是这样的:
const string start = @"(\p{Lu}|\p{Ll}|\p{Lt}|\p{Lm}|\p{Lo}|\p{Nl})";
const string extend = @"(\p{Mn}|\p{Mc}|\p{Nd}|\p{Pc}|\p{Cf})";
Regex ident = new Regex(string.Format("{0}({0}|{1})*", start, extend));
s = s.Normalize();
return ident.IsMatch(s);
这篇关于有没有在C#中的方法来检查一个字符串是否是一个有效的标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文