-1

How do i write regular expression to pass the following?

LastName
LastName SecondLastName
LastName-SecondLastName
LastName, F
LastName SecondLastName, F
LastName-SecondLastName, F
LastName, FirstName
LastName SecondLastName, FirstName
LastName-SecondLastName, FirstName
LastName SecondLastName, FirstName SecondFirstName
LastName SecondLastName, FirstName-SecondFirstName
LastName-SecondLastName, FirstName-SecondFirstName

At the same time, atleast the following should fail:

Any special Character (,?!#@%* etc) at the begining
,FirstName
, FirstName
LastName,
LastName,Any special Character (,?!#@%* etc)
LastName,FirstName

Basically, after a comma, there should be a space and alpha character(s)

Resources:

https://regex101.com/

[A-Za-z]+,\s+[A-Za-z]+

Thanks in advance! :)

Komengem
  • 3,662
  • 7
  • 33
  • 57
  • 1
    Possible duplicate of [Learning Regular Expressions](http://stackoverflow.com/questions/4736/learning-regular-expressions) – Biffen Oct 13 '16 at 20:22
  • Also: http://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/ – Biffen Oct 13 '16 at 20:22
  • Maybe `^([-a-z]+(?: [-a-z ]+)?|[-a-z ]+, [-a-z ]+)$` with `m` and `i` modifier. https://regex101.com/r/KFog8L/3 – chris85 Oct 13 '16 at 20:48
  • Use [`^(?>\p{L}\p{M}*)+(?:(?:, |[ -])(?>\p{L}\p{M}*)+)?(?:, (?>\p{L}\p{M}*)|, (?>\p{L}\p{M}*)+(?:[ -](?>\p{L}\p{M}*)+)?)?$`](http://regexstorm.net/tester?p=%5e(%3f%3e%5cp%7bL%7d%5cp%7bM%7d*)%2b(%3f%3a(%3f%3a%2c+%7c%5b+-%5d)(%3f%3e%5cp%7bL%7d%5cp%7bM%7d*)%2b)%3f(%3f%3a%2c+(%3f%3e%5cp%7bL%7d%5cp%7bM%7d*)%7c%2c+(%3f%3e%5cp%7bL%7d%5cp%7bM%7d*)%2b(%3f%3a%5b+-%5d(%3f%3e%5cp%7bL%7d%5cp%7bM%7d*)%2b)%3f)%3f%5cr%3f%24&i=LN%0d%0aL+S%0d%0aLN-SN%0d%0aLN%2c+F%0d%0aLN+SN%2c+F%0d%0aLN-SN%2c+F%0d%0aLN%2c+FN%0d%0aLN+SN%2c+FN%0d%0aLN-SN%2c+FN%0d%0aLN+SN%2c+FN+SFN%0d%0aLN+SN%2c+FN-SFN%0d%0aLN-SLN%2c+FN-SFN&o=m) – Wiktor Stribiżew Oct 13 '16 at 21:15
  • @Wiktor is that monstrosity really necessary? – CodeCaster Oct 14 '16 at 09:34
  • @CodeCaster: How else are going to match Vietnamese, or other languages that use diacritics? – Wiktor Stribiżew Oct 14 '16 at 09:50
  • @Wiktor I know about [Falsehoods Programmers Believe About Names | Kalzumeus Software](https://www.kalzumeus.com/2010/06/17/falsehoods-programmers-believe-about-names/), but it wasn't in the question, and the expression you posted looks rather ... unintelligible. – CodeCaster Oct 14 '16 at 09:54
  • 2
    @CodeCaster: Precise and efficient regexps for complex scenarios are bound to look unintelligible. – Wiktor Stribiżew Oct 14 '16 at 09:57

1 Answers1

1

How about you try something like:

^[a-zA-Z]+([- ][a-zA-Z]+)?(, [a-zA-Z]+([- ][a-zA-Z]+)?)?$

Example: https://regex101.com/r/ipffrk/3

Addison
  • 7,322
  • 2
  • 39
  • 55