3

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 2

3

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
Sign up to request clarification or add additional context in comments.

5 Comments

he still needs a positive assertion check in addition to the negative case. Allowing "not failure" isn't sufficient for success.
@Mike: I'm not sure I understand your point. would you have an example of what this would not work on?
your regex still passes "_2", which is not a capital letter
@Mike: "_2" matches that RE, which means the string is "malformed". "_A" doesn't match, which means it's "ok".
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 :)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.