2016-09-17 82 views
0

我有一个场景,用户必须在单个字段中输入其第一个名称和姓氏,因此必须在2个名称之间存在空格,至少是一个角色。我试图使用contains(""),但如果用户只输入一个空格并且在该空格之后没有输入任何内容,则此方法返回true。在单个字段中名字和姓氏的正则表达式

请引导我达到此目的。我也试图搜索Regular Expression但未能找到任何。

+0

是,我想对此进行验证,如果用户没有在空格后输入单个字母,我会阻止他 – Kirmani88

回答

0

这里是正则表达式和测试:

@Test 
public void test_firstAndLastName_success() { 
    Pattern ptrn = Pattern.compile("(\\w+)\\s+(\\w+)"); 
    Matcher matcher = ptrn.matcher("FirstName LastName"); 
    if (matcher.find()) { 
    Assert.assertEquals("FirstName", matcher.group(1)); 
    Assert.assertEquals("LastName", matcher.group(2)); 
    } else { 
    Assert.fail(); 
    } 
} 

验证是matcher返回上findfalse

如果您不希望允许多个空格(\s+),那么要么删除+(这将仍然允许单个标签),或者用空格代替它。

0

您可以使用这样的代码:

public static void main(String[] args) throws IOException { 
    String input = "first last"; 
    if (input.matches("[a-zA-Z]*[\\s]{1}[a-zA-Z].*")) { 
     String[] name = input.split(" "); 
     System.out.println(Arrays.toString(name)); 
    } else { 
     System.out.println("Please input the valid name."); 
    } 
} 

它将把姓和名数组,如果:

  • [a-zA-Z]* - 输入与字符开头;
  • [\\s]{1} - 包含只有一个空间;
  • [a-zA-Z].* - 以结尾至少一个字符。
+0

谢谢,但我想在这里进行验证,如果用户在空格后没有输入单个单词,我会告诉他一条警告信息 – Kirmani88

+0

我更新了我的答案。 – DimaSan

0

在修剪字符串之后,使用“”进行简单拆分。

请检查下面的代码为更多的理解:

String[] splitter = null; 

String s = "abbsd sdsdf"; // string with 2 words and space 

    splitter = s.trim().split(" "); 

    if(splitter.length!=2){ 
     System.out.println("Please enter first or last name"); 
    } 
    else{ 
     System.out.println("First Name : "+splitter[0]); 
     System.out.println("Last Name : "+splitter[1]); 
    } 

    s = "abc"; //string without space 

    splitter = s.trim().split(" "); 

    if(splitter.length!=2){ 
     System.out.println("Please enter first or last name"); 
    } 
    else{ 
     System.out.println("First Name : "+splitter[0]); 
     System.out.println("Last Name : "+splitter[1]); 
    } 

请有和没有空间的其他情形进行检查。这应该是有帮助的。

相关问题