简体   繁体   English

正则表达式匹配行,所有单词都以大写开头

[英]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.我正在尝试创建一个正则表达式模式(在 JavaScript 中),该模式匹配所有单词都以大写字母开头的行,无论长度如何。 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.匹配以大写字母开头的单词可以以[AZ]开头,后跟\\w一次或多次。 If you want to match more characters than \\w , you could create a character class [\\w.] to add matching a dot for example.如果你想匹配比\\w更多的字符,你可以创建一个字符类[\\w.]来添加匹配点,例如。

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.它允许任意数量(包括 0)的=符号在任一侧,并要求每个单词以大写字母开头。

The * quantifier means 0 or more times. *量词表示 0 次或多次。

[^ ] is a negated character class, meaning it matches anything except a space. [^ ]是一个否定字符类,这意味着它匹配除空格之外的任何内容。

You can try it online here .您可以在此处在线试用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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