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
2 Answers
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
5 Comments
Mike Pennington
he still needs a positive assertion check in addition to the negative case. Allowing "not failure" isn't sufficient for success.
Mat
@Mike: I'm not sure I understand your point. would you have an example of what this would not work on?
Mike Pennington
your regex still passes "_2", which is not a capital letter
Mat
@Mike: "_2" matches that RE, which means the string is "malformed". "_A" doesn't match, which means it's "ok".
Boaz
thanks @mat. @Mike: I am not interested in the instances themselves, so I have no need in the positive results. but thanks for the second comment because I realized that a number is also legal :)