Boaz
Boaz

Reputation: 5084

checking for validity of a string using regex

I have a string, in which I want to make sure that every '_' is followed by a capital letter. (and I need to do it on one regex) How can I do it? _[A-Z] is good if it finds only one, but will still match if I have: foo_Bar_bad

Upvotes: 3

Views: 100

Answers (2)

Mat
Mat

Reputation: 206689

Do it the other way around with something like:

/_[^A-Z]/

This will match if the string contains _ followed by anything but a capital letter. If it matches, then the string is malformed according to your criteria.

Sample in perl:

$ perl -ne 'if (/_[^A-Z]/) { print "** bad\n" } else { print "** good\n"; };'
qsdkjhf
** good          # no _ at all
qdf_A
** good          # capital after _
qdsf_2
** bad           # no capital after _
qsdf__Aqs  
** bad           # the first _ is followed by another _ => not a capital
_
** bad           # end of input after _ is also rejected

Upvotes: 3

Victor Hurdugaci
Victor Hurdugaci

Reputation: 28425

This might work:

(([_][A-Z])|[^_])+

It will match any character that is not "_" and when it encounters an underscore it will match only if is followed by a capital letter.

Upvotes: 0

Related Questions