我需要一个正则表达式来验证字符串。
string test = "C:\Dic\<:Id:>.<:Dic:>testtest<:Location:>.Test.doc"
我让我使用正则表达式来获取&#34;&lt;:&#34;之间的所有字段。和&#34;:&gt;&#34;。
Regex.Matches(fileNameConfig, @"\<(.+?)\>")
.Cast<Match>()
.Select(m => m.Groups[0].Value).ToList();
现在,我需要检查是否有任何打开的标签没有关闭标签,并且是否有任何嵌套标签。
string test = "C:\Dic\<:<:Id:>.<:Dic:>testtest<:Location:>.Test.doc"
string test = "<:C:\Dic\<:Id:>.<:Dic:>testtest<:Location:>.Test.doc:>"
答案 0 :(得分:1)
可以通过计算开始和结束括号来测试嵌套。
在字符串中的任何位置,此位置前的左括号数必须大于或等于右括号的数量。
在字符串的末尾,开括号的数量必须恰好等于右括号的数量。
public static bool IsBracketNestingValid(string input) {
if (string.IsNullOrWhiteSpace(input)) {
return true; // empty string is always nested correctly
}
const string openingBracket = "<:";
const string closingBracket = ":>";
if (input.Length < openingBracket.Length) {
// perform this check if we expect that input strings
// must contain at least one bracket (e.g. "<" should be invalid)
return false;
}
int openingCount = 0;
int closingCount = 0;
for (int pos = 0; pos < input.Length-1; pos++) {
string currentToken = string.Format("{0}{1}", input[pos], input[pos+1]);
if (currentToken == openingBracket) {
openingCount++;
// skip over this recognized token
// (so we do not count any ':' twice, e.g. "<:>" should be invalid)
pos++;
}
if (currentToken == closingBracket) {
closingCount++;
pos++; // skip over this recognized token
}
if (closingCount > openingCount) {
return false; // found closing bracket before opening bracket
}
}
return openingCount == closingCount;
}