简体   繁体   English

正则表达式匹配单个名字字符串或首字母和姓氏字符串,一个空格和一个连字符

[英]Regular expression to match single first name string or first and last name string with one space and one hyphen

Regular expression to match single first name string or first and last name string with one space and one hyphen. 正则表达式匹配单个名字字符串或首字母和姓氏字符串,一个空格和一个连字符。

Valid matches 有效的比赛

  1. Mathias d-arras Mathias d-arras
  2. Martin Luther 马丁路德
  3. Hector-Sausage 赫克托 - 香肠
  4. Mathias 马蒂亚斯
  5. John-Paul Mathias 约翰 - 保罗马蒂亚斯
  6. Jhon S Jhon S.
  7. K Jhon K Jhon
  8. k jhon-m k jhon-m
  9. Jm k Jm k
  10. k jm k jm

Invalid matches 匹配无效

  1. Mathias d arras Mathias d arras
  2. Mathias- darras 马蒂亚斯达拉斯
  3. Hector -Sausage Hector -Sausage
  4. Hector Sau K Hector Sau K.
  5. Hector-Sau-K 赫克托 - 秀-K
  6. Hector Sausage- Hector Sausage-
  7. aa aa-a aa aa-a
  8. aa aa a aa aa a
  9. Jean-Paul Simmons-Beckett 让 - 保罗西蒙斯 - 贝克特
  10. aa aa aa aa
  11. aaa AAA

Try this: 尝试这个:

/^[a-z]+(?:-[a-z]+)?(?:\s[a-z]+(?:-[a-z]+)?)$/gim

DEMO DEMO

This pattern will correctly match the sample data that you provided (I'm assuming that you actually only want to allow spaces [ 此模式将正确匹配您提供的示例数据(我假设您实际上只想允许空格[ ], not all whitespaces [ \\s ], which would also include tabs, line breaks, etc): ],不是所有的空格[ \\s ],还包括标签,换行符等):

/^[a-z]+( [a-z][a-z-]+||-[a-z]+)?$/i

Though, I wonder if there aren't some other situations that you've missed in your sample data, such as: 但是,我想知道您的样本数据中是否没有其他情况,例如:

  • John-Paul Mathias (valid, but would fail?) John-Paul Mathias (有效,但会失败吗?)
  • Hector Sausage- (invalid, but would pass?) Hector Sausage- (无效,但会通过?)

There would need to be some more tweaks to handle those, if they are needed. 如果需要,还需要进行一些调整来处理这些问题。

Also, I left out the g and m flags, since this looks like a pattern validation, in which case, I wouldn't think you would need them. 另外,我省略了gm标志,因为这看起来像模式验证,在这种情况下,我认为你不会需要它们。 If you actually need to capture multiple instances of this pattern in a multi-line situation, then, you would need those flags put back in. 如果您确实需要在多行情况下捕获此模式的多个实例,那么您需要放回这些标记。

UPDATE UPDATE

Okay, based on those other pieces of test data, the following regex will work: 好的,基于其他测试数据,以下正则表达式将起作用:

/^[a-z]+-?[a-z]+( [a-z]+-?[a-z]+)?$/i

I keep feeling like there is a way to trim it down even more, but the complex relationship between the 我一直觉得有一种方法可以减少它,但是它之间的复杂关系 and - characters are making it difficult. 而且-人物正在变得困难。

UPDATE #2: 更新#2:

Updated to match even more sample data. 已更新以匹配更多样本数据。 :D :d

/^[a-z]+(-[a-z]+)?( [a-z]+(-[a-z]+)?)?$/i

UPDATE #3: 更新#3:

Okay . 好的 。 . . one more update, for the new "one hyphen" requirement. 另一个更新,为新的“连字符”要求。 :) :)

/^[a-z]+(-[a-z]+( [a-z]+)?||( [a-z]+)(-[a-z]+)?)?$/i

please try this pattern : 请尝试这种模式:

/^[a-z]+\s?[a-z]+\-?[a-z]+$/gim

ok , i updated it for you 好的,我为你更新了它

DEMO :P 演示 :P

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM