简体   繁体   中英

Javascript Regex - match capital/upperacase letter in a middle of a word (in a sentence)?

I need to match all capital letters only if they are in a middle of the word. For exmaple RegExr would have a match for letter E . someThings for letter T . If capital letter start at the start of of the word it should not match.

This regex almost match it, but it actually matches both lower case next to upper case letter.

/[a-z][A-Z]/g

For example for word RegExr , it matches gE , but I need to match only E .

update

Updated title to specify that this case happens in a sentence, not single word.

You might be able to use non-word-boundaries here. Word characters ( \\w ) are letters [a-zA-Z] , numbers [0-9] and the underscore _ .

By using \\B[AZ]\\B you can match every uppercase letter, that is inside a word. This will also match:

  • 9Gag
  • _H_ello

This should do it:

/\B[A-Z]\B/g

Use \\B for word boundries

See here for tests and explanation.

The solution using RegExp.prototype.exec() function:

 var str = 'RegExr someTextBetween JavaScript', matched = [], re = /[^AZ\\s]([AZ])[^AZ\\s]/g; while ((m = re.exec(str)) !== null) { matched.push(m[1]); } console.log(matched); 

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