-1

I have the following regular expression for one of my name fields in C# web app:

^[A-Za-zÀ-ſ0-9.,#&-/'_!@;]?[a-zA-ZÀ-ſ0-9 '#&-/.,_:!@;]*[A-Za-zÀ-ſ0-9.,#-/_!@;]$

How can I properly modify it to add apostrophe/single quote character (') as an allowed character to it?

Patrick Hofman
  • 153,850
  • 22
  • 249
  • 325
Tom S
  • 127
  • 1
  • 4
  • 18
  • 1
    Doesn't it already? https://regex101.com/r/mJ0lX9/1 – Patrick Hofman Jun 29 '16 at 07:16
  • 1
    with slash, like this \' – Michał M Jun 29 '16 at 07:18
  • 1
    or put an `@` before the string to make it [raw string](https://msdn.microsoft.com/en-us/library/aa691090%28v=vs.71%29.aspx) – phuclv Jun 29 '16 at 07:32
  • It doesn't for some reason. public const string REGEX_NAME = "^[A-Za-z\u00C0-\u017F0-9.,#&-/'_!@;]?[a-zA-Z\u00C0-\u017F0-9 '#&-/.,_:!@;]*[A-Za-z\u00C0-\u017F0-9.,#-/_!@;]$"; (when debugging , the REGEX_NAME value displays as the string I pasted earlier) The following returns false: Regex.IsMatch("Peter's String", FieldRuleConstants.REGEX_NAME) – Tom S Jun 29 '16 at 07:39
  • it might be something wrong with the existing RegEx but making it raw string has not helped in my case :( – Tom S Jun 29 '16 at 10:20

2 Answers2

1

' is used for declaring a char, so put a backslash in front of the ' to escape it, like this \'.

  • Can you please advise where should it be put in my RegEx? Again, this is how my RegEx string is definded: "^[A-Za-z\u00C0-\u017F0-9.,#&-/'_!@;]?[a-zA-Z\u00C0-\u017F0-9 '#&-/.,_:!@;]*[A-Za-z\u00C0-\u017F0-9.,#-/_!@;]$" – Tom S Jun 29 '16 at 07:41
  • Your code should be `public const string REGEX_NAME = "^[A-Za-z\u00C0-\u017F0-9.,#&-/'!@;]?[a-zA-Z\u00C0-\u017F0-9 '#&-/.,:!@;]*[A-Za-z\u00C0-\u017F0-9.,#-/_!@;]$";` –  Jun 29 '16 at 07:56
  • Tried it but it still fails. Backslashed in front of the apostrophes do not seem to be visible when debugging. I also used '\u005C' instead of '\' but still no success. – Tom S Jun 29 '16 at 10:23
0

It turned out that the RegEx has been fine, and it was the way the data has been input into database that caused the problem. Insert statements should have the apostrophes escaped. Even though the apostrophes were getting displayed correctly, they had been failing the RegEx check due to lack of escaping apostrophes. Thanks for your advice and sorry in case of any disapointment!

Tom S
  • 127
  • 1
  • 4
  • 18