Don't forget about names like:

  • Mathias d'Arras
  • Martin Luther King, Jr.
  • Hector Sausage-Hausen

This should do the trick for most things:

/^[a-z ,.'-]+$/i

OR Support international names with super sweet unicode:

/^[a-zA-ZàáâäãåąčćęèéêëėįìíîïłńòóôöõøùúûüųūÿýżźñçčšžæÀÁÂÄÃÅĄĆČĖĘÈÉÊËÌÍÎÏĮŁŃÒÓÔÖÕØÙÚÛÜŲŪŸÝŻŹÑßÇŒÆČŠŽ∂ð ,.'-]+$/u

Answer from maček on Stack Overflow
🌐
RegExr
regexr.com › 3f8cm
First/Last Name Validator
Build a suite of tests that your expression should (or should not) match. Create new tests with the 'Add Test' button. Click a test to edit the name, type, & text.
Discussions

regex - Regular expression for validating names and surnames? - Stack Overflow
Explore Stack Internal ... I need to validate names and surnames of people from all over the world. Imagine a huge list of miilions of names and surnames where I need to remove as well as possible any cruft I identify. How can I do that with a regular expression? More on stackoverflow.com
🌐 stackoverflow.com
regular expression to catch names - C++ Forum
Given expression: ... By the way, you ask for strings of at least 2 elements. ... @duoas: i was using the pipes for or. i am still relatively new to re's and didnt know that i could do without them. and yeah its copying it because its doing it for words that i know there is only one of. @everyone: is it my code then? i switched the re to one suggested and its still doing it. could it be something in ... More on cplusplus.com
🌐 cplusplus.com
Is there a way to validate the syntax of regex pattern using C code - Stack Overflow
I do not want to use live testing ... do the validation in code itself (C or C++) 2019-02-01T11:37:22.077Z+00:00 ... C is what i want, if there is no way out in C, then C++ is the second option. 2019-02-01T11:41:42.817Z+00:00 ... There are regex libraries for c you can use (see Regular expressions in C: ... More on stackoverflow.com
🌐 stackoverflow.com
regular expressions - Best REGEX for first/last name validation? - Salesforce Stack Exchange
The Len & Mid bits are to stop initials, or people putting in "S J ". There is probably a more elegant way of doing this but I'm rather fresh to REGEX. ... Be careful when "validating" names. Anything more than verifying a reasonable length (1kb?) for names will be too restrictive. ... Related: Regex use vs. Regex abuse & When you should NOT use Regular Expressions... More on salesforce.stackexchange.com
🌐 salesforce.stackexchange.com
🌐
NYC PHP Developer
andrewwoods.net › blog › 2018 › name-validation-regex
Name Validation Regex for People's Names | NYC PHP Developer | Andrew Woods
September 19, 2018 - It’s developers not making the most of their capabilities. In this article, we’ll walk through the process of building up a regular expression, and discuss the various decision points along the way. This should help you adapt the name validation regex to meet your specific needs.
🌐
regex101
regex101.com › library › gK4eN5
regex101: Name Validation
if you are as lazy as me and want to replace every "=$_POST['name'];" using Dreamweaver or any development tool that allows using regular expressions to search in current file/document.Submitted by Kevinator ... Validates hexadecimal color codes based on the following rule set: Optionally starting with a hash.
Top answer
1 of 14
47

I sympathize with the need to constrain input in this situation, but I don't believe it is possible - Unicode is vast, expanding, and so is the subset used in names throughout the world.

Unlike email, there's no universally agreed-upon standard for the names people may use, or even which representations they may register as official with their respective governments. I suspect that any regex will eventually fail to pass a name considered valid by someone, somewhere in the world.

Of course, you do need to sanitize or escape input, to avoid the Little Bobby Tables problem. And there may be other constraints on which input you allow as well, such as the underlying systems used to store, render or manipulate names. As such, I recommend that you determine first the restrictions necessitated by the system your validation belongs to, and create a validation expression based on those alone. This may still cause inconvenience in some scenarios, but they should be rare.

2 of 14
19

I'll try to give a proper answer myself:

The only punctuations that should be allowed in a name are full stop, apostrophe and hyphen. I haven't seen any other case in the list of corner cases.

Regarding numbers, there's only one case with an 8. I think I can safely disallow that.

Regarding letters, any letter is valid.

I also want to include space.

This would sum up to this regex:

^[\p{L} \.'\-]+$

This presents one problem, i.e. the apostrophe can be used as an attack vector. It should be encoded.

So the validation code should be something like this (untested):

var name = nameParam.Trim();
if (!Regex.IsMatch(name, "^[\p{L} \.\-]+$")) 
    throw new ArgumentException("nameParam");
name = name.Replace("'", "'");  //' does not work in IE

Can anyone think of a reason why a name should not pass this test or a XSS or SQL Injection that could pass?


complete tested solution

using System;
using System.Text.RegularExpressions;

namespace test
{
    class MainClass
    {
        public static void Main(string[] args)
        {
            var names = new string[]{"Hello World", 
                "John",
                "João",
                "タロウ",
                "やまだ",
                "山田",
                "先生",
                "мыхаыл",
                "Θεοκλεια",
                "आकाङ्क्षा",
                "علاء الدين",
                "אַבְרָהָם",
                "മലയാളം",
                "상",
                "D'Addario",
                "John-Doe",
                "P.A.M.",
                "' --",
                "<xss>",
                "\""
            };
            foreach (var nameParam in names)
            {
                Console.Write(nameParam+" ");
                var name = nameParam.Trim();
                if (!Regex.IsMatch(name, @"^[\p{L}\p{M}' \.\-]+$"))
                {
                    Console.WriteLine("fail");
                    continue;
                }
                name = name.Replace("'", "&#39;");
                Console.WriteLine(name);
            }
        }
    }
}
🌐
Regex Pattern
regexpattern.com › home › name validation regular expression
Name Validation Regular Expression - Regex Pattern
March 17, 2022 - A regular expression that matches and validates people's names (first name, middle name, last name).
🌐
C# Corner
c-sharpcorner.com › UploadFile › 87b416 › validating-user-input-with-regular-expressions
Validating User Input With Regular Expressions
February 14, 2022 - The code above calls the firstNameTextBox's Focus method to place the cursor in the firstNameTextBox. If there are no empty fields, then the following code validates the first name by calling the static method Match of the Regex class, passing both the string to validate and the Regular Expression as arguments.
Find elsewhere
🌐
Cplusplus
cplusplus.com › forum › general › 111329
regular expression to catch names - C++ Forum
BTW, remember that an RE will glob as much as it can, so you need to give it an opportunity to stop. Also, I'm not sure what the pipes are there for. [_a-zA-Z][_a-zA-Z0-9]* should work. If you can, use character classes/bracket expressions: (_|[:alpha:])\w* This will work with Unicode text ...
🌐
Stack Overflow
stackoverflow.com › questions › 54478448 › is-there-a-way-to-validate-the-syntax-of-regex-pattern-using-c-code
Is there a way to validate the syntax of regex pattern using C code - Stack Overflow
I do not want to use live testing ... do the validation in code itself (C or C++) 2019-02-01T11:37:22.077Z+00:00 ... C is what i want, if there is no way out in C, then C++ is the second option. 2019-02-01T11:41:42.817Z+00:00 ... There are regex libraries for c you can use (see Regular expressions in C: ...
🌐
Quora
quora.com › What-is-the-regular-expression-to-extract-only-variable-names-from-a-C-file-and-use-it-to-validate
What is the regular expression to extract only variable names from a C file and use it to validate? - Quora
Answer: No regular expression can do that for you. You need a full-blown C-parser to extract variable names. You will also need to maintain a symbol table, so you can tell variable names apart from type names and function names.
🌐
Laasya Setty Blogs
laasyasettyblog.hashnode.dev › validating-username-using-regex
Validating Username Using REGEX. - Laasya Setty Blogs
November 28, 2020 - A valid username should start with an alphabet so, [A-Za-z]. All other characters can be alphabets, numbers or an underscore so, [A-Za-z0-9_]. Since length constraint was given as 8-30 and we had already fixed the first character, so we give ...
Top answer
1 of 7
12

A pattern to recognize variable declarations in C. Looking at a conventional declaration, we see:

int variable;

If that's the case, one should test for the type keyword before anything, to avoid matching something else, like a string or a constant defined with the preprocessor

(?:\w+\s+)([a-zA-Z_][a-zA-Z0-9]+)

variable name resides in \1.

The feature you need is look-behind/look-ahead.

UPDATE July 11 2015

The previous regex fail to match some variables with _ anywhere in the middle. To fix that, one just have to add the _ to the second part of the first capture group, it also assume variable names of two or more characters, this is how it looks after the fix:

(?:\w+\s+)([a-zA-Z_][a-zA-Z0-9_]*)

However, this regular expression has many false positives, goto jump; being one of them, frankly it's not suitable for the job, because of that, I decided to create another regex to cover a wider range of cases, though it's far from perfect, here it is:

\b(?:(?:auto\s*|const\s*|unsigned\s*|signed\s*|register\s*|volatile\s*|static\s*|void\s*|short\s*|long\s*|char\s*|int\s*|float\s*|double\s*|_Bool\s*|complex\s*)+)(?:\s+\*?\*?\s*)([a-zA-Z_][a-zA-Z0-9_]*)\s*[\[;,=)]

I've tested this regex with Ruby, Python and JavaScript and it works very well for the common cases, however it fails in some cases. Also, the regex may need some optimizations, though it is hard to do optimizations while maintaining portability across several regex engines.

Tests resume

unsignedchar *var;                   /* OK, doesn't match */
goto **label;                        /* OK, doesn't match */
int function();                      /* OK, doesn't match */
char **a_pointer_to_a_pointer;       /* OK, matches +a_pointer_to_a_pointer+ */
register unsigned char *variable;    /* OK, matches +variable+ */
long long factorial(int n)           /* OK, matches +n+ */
int main(int argc, int *argv[])      /* OK, matches +argc+ and +argv+ (needs two passes) */
const * char var;                    /* OK, matches +var+, however, it doesn't consider +const *+ as part of the declaration */
int i=0, j=0;                        /* 50%, matches +i+ but it will not match j after the first pass */
int (*functionPtr)(int,int);         /* FAIL, doesn't match (too complex) */

False positives

The following case is hard to cover with a portable regular expression, text editors use contexts to avoid highlighting text inside quotes.

printf("int i=%d", i);               /* FAIL, match i inside quotes */

False positives (syntax errors)

This can be fixed if one test the syntax of the source file before applying the regular expression. With GCC and Clang one can just pass the -fsyntax-only flag to test the syntax of a source file without compiling it

int char variable;                  /* matches +variable+ */
2 of 7
4
[a-zA-Z_][a-zA-Z0-9_]{0,31} 

This will allow you to have variable names as "m_name" validated.

🌐
CodePal
codepal.ai › regex generator › regex for name validation
Regex for Name Validation - CodePal
October 16, 2024 - Learn how to create a regular expression for validating names with specific formatting rules.
🌐
GeeksforGeeks
geeksforgeeks.org › c language › regular-expressions-in-c
Regular expressions in C - GeeksforGeeks
July 12, 2025 - ... where, regex = precompiled ... shown below: ... REG_NOMATCH: If there is no match. Below is the illustration of the regexec() function: ... // C program to illustrate the regexec() function #include <regex.h> #include <stdio.h> ...
🌐
Guidanceshare
guidanceshare.com › wiki › Validate_User_Input_with_Regular_Expressions_-_C
Validate User Input with Regular Expressions - C - Guidance Share
October 19, 2006 - Application makes use of data that comes from any other untrusted source, such as a third-party data feed or file upload. Application does not already make use a validation scheme for input data. The solution example defines 16 regular expression validation functions and a helper method that address a common set of application input data types.
🌐
Quora
quora.com › How-do-I-validate-this-input-in-C
How to validate this input in C - Quora
Answer (1 of 3): When it comes to input validation, regular expressions are a popular language-agnostic choice, with Regex implementations in many languages, C being no exception. And even if you cannot use a Regex library, such as in embedded systems, you can convert Regex into C code automatica...
🌐
O'Reilly
oreilly.com › library › view › regular-expressions-cookbook › 9780596802837 › ch04.html
4. Validation and Formatting - Regular Expressions Cookbook [Book]
Chapter 4. Validation and FormattingThis chapter contains recipes for validating and formatting common types of user input. Some of the solutions show how to allow... - Selection from Regular Expressions Cookbook [Book]