如何只测试字母或撇号的字符串?

时间:2015-09-06 10:26:17

标签: java vb.net string

我需要检查字符串以获取一些东西:

  1. 第一个字母必须是大写字母
  2. 只有字母或撇号(')
  3. 最多可以使用2个撇号
  4. 下面的代码总是返回字符串不符合,除非我只输入1个大写字母。我如何纠正它以满足我的要求?

    Private Function setName(ByVal pName As String)
        Dim letters As Integer()
        Dim aphCount As Integer = 0
        Dim isvalid As Boolean = True
        For i As Integer = 0 To pName.Length - 1 Step 1
            ReDim letters(i)
            letters(i) = Asc(pName.Substring(i, 1))
        Next
    
        If Not letters(0) >= 65 And letters(0) <= 90 Then
            isvalid = False
        End If
    
        For i As Integer = 1 To pName.Length - 1 Step 1
            If letters(i) >= 39 And letters(i) <= 122 Then
                If letters(i) = 39 Then
                    aphCount += 1
                    If aphCount > 2 Then
                        isvalid = False
                    End If
                ElseIf letters(i) >= 65 And letters(i) <= 90 Then
    
                ElseIf letters(i) >= 97 And letters(i) <= 122 Then
    
                Else isvalid = False
                End If
            Else isvalid = False
            End If
        Next
    
        If isvalid = False Then
            If MsgBox("you put in an invalid name", MsgBoxStyle.RetryCancel, "name error") = MsgBoxResult.Cancel Then
                pName = "Hero" & heroCount
            Else
                pName = inputName()
                pName = setName(pName)
            End If
        End If
        Return pName
    End Function
    

    编辑:谢谢大家的帮助,我学习正则表达式并想出了一些有用的东西(使用java,我切换到java,因为这是一个让我学习编码的项目,java有更多提供):< / p>

    public void checkName(String name)  throws IllegalArgumentException{
         String noSpaceName = name.replaceAll("\\s+","");
         String pattern = "^[A-Z][A-Za-z]*'?[A-Za-z]*'?[A-Za-z]*";    
         Pattern re = Pattern.compile(pattern);
         Matcher m = re.matcher(noSpaceName);
         if (m.matches()){
             name.replaceAll("\\s+"," ");
             super.setName(name);
         }else throw new IllegalArgumentException ("Exception: Name is invalid");
    }
    

2 个答案:

答案 0 :(得分:1)

您的代码对于您要执行的操作非常复杂。它很长,它包含很多magic numbers。您可以使用正则表达式或通过定期比较字符串中的每个元素来解决此问题。这是第二种方式的例子:

Private Function IsValidName(name As String) As Boolean
    If String.IsNullOrWhiteSpace(name) Then Return False

    Return Char.IsUpper(name.AsEnumerable().First()) AndAlso
           name.AsEnumerable().All(Function(c) Char.IsLetter(c) OrElse c.Equals("'"c)) AndAlso
           name.AsEnumerable().Count(Function(c) c.Equals("'"c)) <= 2
End Function

答案 1 :(得分:1)

你可以用两行正则表达式来做到这一点。

Private Function IsValidName(name As String) As Boolean
    Dim match = Regex.Match(name, "^[A-Z]((')|[A-Za-z])*$")
    Return match.Success AndAlso match.Groups(2).Captures.Count <= 2
End Function