最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - Only select words with all lower case characters javascript - Stack Overflow

programmeradmin0浏览0评论

I am trying to write a regex to match only words that contain only un-capitalized letters in a string, but cannot figure it out.

Example

var str = "What a wonderful Sunday Afternoon";

I have managed to match any words beginning with a capital letter using this regex var str1 = str.match(/[A-Z][a-z]+/g)

Here str1 returns [What, Sunday, Afternoon]

What I now want to do is write a regex that returns a and wonderful.

I am trying to write a regex to match only words that contain only un-capitalized letters in a string, but cannot figure it out.

Example

var str = "What a wonderful Sunday Afternoon";

I have managed to match any words beginning with a capital letter using this regex var str1 = str.match(/[A-Z][a-z]+/g)

Here str1 returns [What, Sunday, Afternoon]

What I now want to do is write a regex that returns a and wonderful.

Share Improve this question edited Nov 22, 2015 at 15:52 Josh Crozier 241k56 gold badges400 silver badges313 bronze badges asked Nov 22, 2015 at 15:32 Paul FitzgeraldPaul Fitzgerald 12.1k4 gold badges45 silver badges57 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 5

You don't need regular expressions for this.

Just split the string at whitespace, and then filter the array based on whether the word is lowercase.

Example Here

var string = "What a wonderful Sunday Afternoon";
var lowerCaseWords = string.split(' ').filter(function(word) {
  return word === word.toLowerCase();
});

console.log(lowerCaseWords);
// ["a", "wonderful"]

You could use this regex.

\b([a-z]+)\b

Demo: https://regex101./r/uQ6lT4/1

Your current regex [A-Z][a-z]+

Says one capital letter then any amount of lowercase letters.

Without the [A-Z] you're are just looking for all lowercase letters, so partial words are matched. Adding word boundaries will ensure the value is one word (excluding hyphenated words).

you can also use below approach

var string = "What a wonderful Sunday Afternoon";
string .split(' ').forEach(function(v,k){
if(/[a-z]/.test(v.charAt(0))){
console.log(v);
return v;
}
})

    var string = "What a wonderful Sunday Afternoon";
    string .split(' ').forEach(function(v,k){
    if(/[a-z]/.test(v.charAt(0))){
    console.log(v);
    return v;
    }
    })

发布评论

评论列表(0)

  1. 暂无评论