Domanda

I'm writing a data annotation in an MVC application. I need to apply a RegEx for the following:

  • Must start with an alphabetic char,
  • Must end with an alphabetic char,
  • Can only contain alphabetic, periods/full stops, spaces, apostrophes and hyphens.

I'm trying the following and would appreciate a point in the right direction:

^[A-Za-z][A-Za-z|.| |'|-]*(?:[A-Za-z])*$

Effectively it's appearing to do what I want, EXCEPT that it allows periods, hyphens, spaces and apostrophes at the end of the string. I thought I had cracked it, but instead, I'm turning to you SO.

Any help would be very much appreciated!!

EDIT: Just in case anyone is after the solution to a very similar problem:

^[A-Za-z][A-Za-z|.| |'|-]*[A-Za-z]$
È stato utile?

Soluzione

Just remove the lookahead at the very end of your regex and you should be done.

/^[A-Za-z][A-Za-z|.| |'|-]*[A-Za-z]$/g

What you want to make sure, is that the very last letter of your match is a letter, so there is no need to have a lookahead. You can just match it like you would do with any normal letter.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top