I have some text that could look something like this:
Name is William Bob Francis Ford Coppola-Mr-Cool King-Of-The-Mountain is a fake name.
I would like to run a regular expression against that string and pull out
William Bob Francis Ford Coppola-Mr-Cool King-Of-The-Mountain
as a match.
My current regex looks like this:
/\b((NAME\s\s*)(((\s*\,*\s*)? *)(([A-Z\'\-])([A-Za-z\'\-]+)*\s*){2,})?)\b/ig
and it does most of what I want but it's not perfect. Instead of just getting the name, it is also getting the "is a" following the name like this:
"William Bob Francis Ford Coppola-Mr-Cool King-Of-The-Mountain is a"
What is a regex formula to get only the words starting with a capital letter following the "Name" label and end when the next word starts with a lowercase after a space?
To use a keyboard shortcut to change between lowercase, UPPERCASE, and Capitalize Each Word, select the text and then press fn+ SHIFT + F3 until the style you want is applied.
replace(/\b\w/g, c => c. toUpperCase()); The regular expression basically matches the first letter of each word within the given string and transforms only that letter to uppercase.
To check if a letter in a string is uppercase or lowercase use the toUpperCase() method to convert the letter to uppercase and compare it to itself. If the comparison returns true , then the letter is uppercase, otherwise it's lowercase. Copied!
Title case, which capitalizes the first letter of certain key words. Sentence case, in which titles are capitalized like sentences. Initial case, where the first letter of every word is capitalized.
How do you like /Name ((?:[A-Z]\w+[ -]?)+)/
?
Regex101: https://regex101.com/r/BFJBpZ/1
You can use:
Name\b[\sa-z]*\K(?:[A-Z][a-z]+[\s-]*)+(?=\s[a-z])
where
\K
resets the starting point of the matching after having matched Name
followed by some words in lower case(?:[A-Z][a-z]+[\s-]*)+
will match all the words starting with a capital letter(?=\s[a-z])
add the constraint that the following word starts with a lower case letterdemo: https://regex101.com/r/WBrdFU/1/
Notes:
you shouldn't use the
i
option in your regex, if you do so all of your char classes[A-Z]
will at the same time match upper case letters but also lower case letters... This would prevent you from selecting the words that start with a capital letter!!!
Adding the names with apostrophe:
Name\b[\sa-z]*\K(?:[A-Z][a-z'\s-]*?)+(?=\s[a-z])
demo: https://regex101.com/r/WBrdFU/3/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With