使用RegEx验证Java中的名字和姓氏 [英] Using RegEx for validating First and Last names in Java

查看:97
本文介绍了使用RegEx验证Java中的名字和姓氏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试验证包含第一个&的String一个人的姓氏.名称的可接受格式如下.

I am trying to validate a String which contains the first & last name of a person. The acceptable formats of the names are as follows.

Bruce Schneier                  
Schneier, Bruce
Schneier, Bruce Wayne
O’Malley, John F.
John O’Malley-Smith
Cher

我想出了以下程序,它将验证String变量.如果名称格式与上述提到的任何格式都匹配,则validateName函数应返回true.否则它应该返回false.

I came up with the following program that will validate the String variable. The validateName function should return true if the name format matches any of the mentioned formats able. Else it should return false.

import java.util.regex.*;

public class telephone {

    public static boolean validateName (String txt){
        String regx = "^[\\\\p{L} .'-]+$";
        Pattern pattern = Pattern.compile(regx, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(txt);
        return matcher.find();

    }

    public static void main(String args[]) {

        String name = "Ron O’’Henry";

        System.out.println(validateName(name));

    }
}

但是由于某种原因,它会返回任何值的false.我在这里做什么错了?

But for some reason, it is returning false for any value. What am I doing wrong here?

推荐答案

使用此:

^[\p{L}\s.’\-,]+$

演示: https://regex101.com/r/dQ8fK8/1

  1. 您遇到的最大问题是'不同.您只能通过复制文本粘贴来实现该字符.
  2. 使用\-代替[]中的-,因为它将被误认为是范围.例如:[a-z]
  3. 您可以使用\s代替来匹配任何空格.
  1. The biggest problem you have is ' and is different. You can only achieve that character by copy pasting from the text.
  2. Use \- instead of - in [] since it will be mistaken as a range. For example: [a-z]
  3. You can use \s instead of for matching any whitespaces.

这篇关于使用RegEx验证Java中的名字和姓氏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆