【问题标题】:Regex for more than 1 First Name before the Middle Initial中间首字母之前超过 1 个名字的正则表达式
【发布时间】:2017-06-28 11:42:19
【问题描述】:

我不太擅长正则表达式,这是我的问题:
我想创建一个与具有两个或多个名字的名称匹配的正则表达式(例如 Francis Gabriel)。

我想出了正则表达式 ^[A-Z][a-z]{3,30}/s[A-Z][a-z]{3,30} 但是 它只匹配两个名字而不是所有名字。

正则表达式应与 John John J. Johnny 匹配。

【问题讨论】:

  • 你用的是什么语言?
  • 我目前正在使用 java
  • 你是如何定义名字的?如何处理名称Francis Scott Key? “斯科特”是中间名还是第二个名字?
  • 我不明白。你可以有几个名字,名字中没有首字母,对吧?所以在首字母之前抓住名字是不够的?

标签: regex


【解决方案1】:
^[A-Z][a-z]{3,30}(\\s[A-Z](\\.|[a-z]{2,30})?)*$

\s 在使用模式编译器时必须在 java 中使用。 如果是 X.,我们必须验证它,或者 XYZ John Johny J.hny -> 错了 所以要么。或 [a-z] 并且至少应该有一个名字。因此,在第二部分的最后加上 * 以匹配 0 或更多。

由于此 sn-p 不支持 java,因此为您提供了相同正则表达式的 JavaScript 实现。

在这里查看

var reg=/^[A-Z][a-z]{3,30}(\s[A-Z](\.|[a-z]{2,30})?)*$/;
console.log(reg.test("John john")); // false because second part start with small case
console.log(reg.test("John John"));
console.log(reg.test("John John J."));
console.log(reg.test("John John J. Johny"));

【讨论】:

  • 啊,所以在正则表达式中使用or 来找到中间的首字母,如果不继续,我是多么愚蠢。谢谢
  • Regex 非常简单,兄弟。如果您查看示例,您将一无所获。所以,学习基础知识。它会帮助你。万事如意
【解决方案2】:

使用以下正则表达式:

^\w+\s(\w+\s)+\w\.\s\w+$

^\w+\s    match a name a space
(\w+\s)+  followed by at least one more name and space
\w+\.\s   followed by a single letter initial with dot then space
\w+$      followed by a last name

Regex101

测试代码:

String testInput = "John John P. Johnny";
if (testInput.matches("^\\w+\\s(\\w+\\s)+\\w+\\.\\s\\w+$")) {
    System.out.println("We have a match");
}

【讨论】:

    【解决方案3】:

    试试这个:

    ^(\S*\s+)(\S*)?\s+\S*?
    

    弗朗西斯·加布里埃尔 - 比赛:

    0: [0,10] Francis 
    1: [0,9] Francis 
    2: [9,9] 
    

    John John2 J. Johnny - 匹配:

    0: [0,11] John John2 
    1: [0,5] John 
    2: [5,10] John2
    

    【讨论】:

    • 先生,正则表达式只会匹配两个名字,而仅仅寻找空格不足以匹配一个或多个名字。
    • 我更新了我的答案。我不清楚你在找什么。也许用更多示例更新您的问题以及您希望结果对我们有所帮助。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多