2

I would like to insert some style tests as git hooks in order to stick with precise style rules. How can I come up with a oneliner that detects and prints arbitrary camelcase variables like the following:

camelCasehere
or
camelCaseHere
or
camel_caseHere
  • 1
    Are these strings in variables or in a file. If in a file, do they occur on a line by themselves, or is the file a full program in some language? How would you envisage matching only variables in that source code in that case? – Kusalananda Mar 8 at 8:12
6

How about

/bin/grep -E '[a-z]{1,}[A-Z]'

This would require that at least one lowercase character is before an uppercase. This would match all your testcases.

If you want to also match something like camel_Case and not Nocamelcase you can use:

/bin/grep -E '([a-z]{1,}[A-Z])|(^.+[A-Z]{1,}[a-z])' 

To test it yourself you can use something like:

cat <<EOF | /bin/grep -E '([a-z]{1,}[A-Z])|(^.+[A-Z]{1,}[a-z])'
NONMATCH                                                               
nonmatch
shouldMatch1
should_Match2
should_mAtch3
Non_match    
Non_MATCH
Should_mAtch4
Should_Match5
EOF
  • The second solution is the best suited. – ziu Jul 31 '12 at 12:03
  • {1,} is better written as + in EREs (shorter and more portable, EREs initially didn't have {x,y}), but anyway grep '[a-z][A-Z]' would achieve the same thing. – Stéphane Chazelas Mar 8 at 8:52
  • What [a-z] matches (and in particular whether it matches some uppercase characters) depends on the system and locale. Using [[:lower:]] and [[:upper:]] would be more appropriate. – Stéphane Chazelas Mar 8 at 8:54
0

Just in case this is useful for somebody, here you are a oneliner to detect PHP variables with Snake Case in code (assumes GNU grep):

grep -r --include='*.php' -E '\$[a-zA-Z]+_[a-zA-Z]' .
  • How would this pick up only variables? – Kusalananda Mar 8 at 8:11
  • PHP variables start with a dollar ($) char, and the regular expression has this consideration. – joan16v Mar 8 at 8:39
  • It misses variables like $foo1_bar – Stéphane Chazelas Mar 8 at 8:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.