简体   繁体   中英

Regex match line with all words starting in uppercase

I am attempting to create a regex pattern (in JavaScript) that matches a line where all the words begin with uppercase letters, regardless of length. It must also account for any number of equals signs ('=') being on either side.

For example
Matches:
==This Would Match==
===I Like My Cats===
====Number Of Equals Signs Does Not Matter===
=====Nor Does Line Length Etc.=====

But
==This would not regardless of its length==
===Nor would this match, etc===

Any help would be greatly appreciated.

You could match one or more equals signs at either side like =+ .

To match words that begin with a capital letter could start with [AZ] followed by \\w one or more times. If you want to match more characters than \\w , you could create a character class [\\w.] to add matching a dot for example.

This pattern would match between equals sign(s) zero or more times a word that starts with an uppercase character followed by a whitespace, and ends with a word that starts with an uppercase character:

^=+(?:[AZ]\\w* )*(?:[AZ][\\w.]+)=+$

 const strings = [ "==This Would Match==", "===I Like My Cats===", "====Number Of Equals Signs Does Not Matter===", "=====Nor Does Line Length Etc.=====", "==This would not regardless of its length==", "===Nor would this match, etc===", "=aaaa=" ]; let pattern = /^=+(?:[AZ]\\w* )*(?:[AZ][\\w.]+)=+$/; strings.forEach((s) => { console.log(s + " ==> " + pattern.test(s)); });

This matches your desired results:

 var test = [ "==This Would Match==", "===I Like My Cats===", "====Number Of Equals Signs Does Not Matter===", "=====Nor Does Line Length Etc.=====", "==This would not regardless of its length==", "===Nor would this match, etc===" ] var reg = /=*([AZ]\\w*\\W*)+=*/g; console.log(test.map(t => t.match(reg) == t));

Try this regex:

^=*[A-Z][^ ]*( [A-Z][^ ]*)*=*$

It allows for any number (including 0) of = signs on either side and requires every word to start with a capital letter.

The * quantifier means 0 or more times.

[^ ] is a negated character class, meaning it matches anything except a space.

You can try it online here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM