求两个正则表达式:判断字符串中是否有重复字符,以及字符是否连续且升序排列。
如题。举例如下:
合法的 非法的
“ABCDEF” “AABBCC”
“ABCDE” “ACDEF”
[解决办法]
用正则没办法吧
[解决办法]
正则没办法,得自己写程序~
[解决办法]
using System;
public class MyClass
{
public static void Main()
{
string str = "A$B1CDE3!F ";
Console.WriteLine(Check(str));
Console.ReadLine();
}
//符合条件返回true,不符合返回false
//注意,如果输入的字符串中不包含字母,也会返回true
public static bool Check(string str)
{
//长度为零
if(str.Length == 0)
{
return false;
}
//临时变量
int asii = -1;
//遍历字符串
foreach(char c in str)
{
//如果不是字母
if(!Char.IsLetter(c))
{
continue;
}
//转成小写字母
Char c2 = Char.ToLower(c);
//如果当前asii为-1,说明是第一个字母,直接赋值
if(asii == -1)
{
asii = (int)c2;
}
else
{
//如果当前字母比前一个字母大一
if(asii == ((int)c2) - 1)
{
//赋值
asii = (int)c2;
continue;
}
else
{
return false;
}
}
}
return true;
}
}
[解决办法]
试试:
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button5.Click
Dim a As String = "A&B&C "
Console.WriteLine(ExpressIsValid(a))
End Sub
Private Function ExpressIsValid(ByVal express As String) As Boolean
Dim pattern As String = "([^A-Z]) "
'将A&B&C转为ABC
Dim charString As String = System.Text.RegularExpressions.Regex.Replace(express, pattern, " ")
If String.IsNullOrEmpty(charString) Then Return False
If charString.Length = 1 Then Return True '只有一个字母
For i As Integer = 1 To charString.Length - 1
If Asc(charString.Chars(i - 1)) + 1 <> Asc(charString.Chars(i)) Then '相邻字母需连续
Return False
End If
Next
Return True
End Function