正则表达式表示中间名首字母前的 1 个以上名字



我对正则表达式不是那么好,这是我的问题:
我想创建一个与具有两个或多个名字的名字匹配的正则表达式(例如弗朗西斯·加布里埃尔(。

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

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

^[A-Z][a-z]{3,30}(\s[A-Z](\.|[a-z]{2,30})?)*$

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

由于此代码段不支持 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"));

使用以下正则表达式:

^w+s(w+s)+w.sw+$
^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

正则表达式101

测试代码:

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

试试这个:

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

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

0: [0,10] Francis 
1: [0,9] Francis 
2: [9,9] 
约翰·约翰

2 约翰尼 - 比赛:

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

最新更新