-2

我有这个正则表达式代码: ^([a-zA-Z]{1,}'?-?\s?[a-zA-z]{1,}'?-?\s[a-zA-Z] {1,}\s?([a-zA-Z]{1,})?)

我可以插入这些名称:

John Smith                                       
John Doe-Smith                                   
John Doe Smith                                   
Hector Sausage-Hausen                            
Mathias Sausage'd                                
Martin Luther King                               
Ai Wong                                          
Chao Chang                                        
Alzbeta Bara
ANDREW ROTARACT
ION-APOSTOL Marius Andrei
ION-APOSTOL Marius Andrei-Mihai
Cosmin Marius-Marian
Cosmin-Marian Marius
John Mc'Largy
Mc'Largy John
D'Largy John
John D'Largy

我希望能够插入至少 2 个字母的名称。即:Co St 我不想输入这些名称:Co s, C St, Henkel1, Kenkel1 Nestle, 12344, Henkel & Henkel (字符如 &,.#%^*()!@~) 和另外,我希望能够添加如下名称:John Mc'Largy

4

3 回答 3

0

您要求的正则表达式是^[A-Za-z][A-Za-z'][A-Za-z-]*\s[A-Za-z]{2,}[A-Za-z\s'-]*$

解释:

  1. 第一个字符应该是字母
  2. 第二个字符应该是字母或'
  3. 在前两个字符之后,可以有任意数量(零个或多个)字母或-后跟一个空格
  4. 在空格之后,应至少有 2 个字母后跟任意数量(零个或多个)的字母、空格-'

检查这个以获得演示和更多解释。

于 2020-07-20T16:35:15.593 回答
0

这个怎么样?

^[a-zA-Z'-]{2,} ([ ]?[a-zA-Z'-]{2,})+$

我是怎么想出来的:

PART 1
  [a-zA-Z'-]                                 = names with letters, quotes and hyphens...
  [a-zA-Z'-]{2,}                             = ... with at least 2 characters

PART 2 (double PART 1)
  [a-zA-Z'-]{2,} [a-zA-Z'-]{2,}              = there must be at least 2 name parts separated with a space
  [a-zA-Z'-]{2,} ([ ]?[a-zA-Z'-]{2,})+       = the last section can be repeated multiple times with an (optional) space in front of each part
 ^[a-zA-Z'-]{2,} ([ ]?[a-zA-Z'-]{2,})+$      = but nothing else on the line
于 2020-07-20T08:53:14.887 回答
0

const regex = /^[a-z-']{2,} ([a-z-']{2,}[ ]?)+$/gim;
const str = `John Smith
John Doe-Smith
John Doe Smith
Hector Sausage-Hausen
Mathias Sausage'd
Martin Luther King
Ai Wong
Mc'Largy John
Co St
Co s
C St
Henkel1
Kenkel1 Nestle
12344
Henkel & Henkel
Max Ap
Max Ap&
Andrew`;

const result = str.match(regex);

console.log(result);

于 2020-07-20T08:40:29.847 回答