Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regexp match any uppercase characters except a particular string

Tags:

regex

I want to match all lines that have any uppercase characters in them but ignoring the string A_

To add to the complication I want to ignore everything after a different string, e.g. an open comment

Here are examples of what should and shouldnt match

Matches:

  • fooBar
  • foo Bar foo
  • A_fooBar
  • fooBar /* Comment */

Non Matches (C_ should not trigger a match)

  • A_foobar
  • foo A_bar
  • foobar
  • foo bar foo bar
  • foobar /* Comment */

thanks :)

like image 991
Alan Avatar asked Nov 03 '09 13:11

Alan


People also ask

How do you match a capital letter in regex?

Using character sets For example, the regular expression "[ A-Za-z] " specifies to match any single uppercase or lowercase letter. In the character set, a hyphen indicates a range of characters, for example [A-Z] will match any one capital letter.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is the difference between () and [] in regex?

In other words, square brackets match exactly one character. (a-z0-9) will match two characters, the first is one of abcdefghijklmnopqrstuvwxyz , the second is one of 0123456789 , just as if the parenthesis weren't there. The () will allow you to read exactly which characters were matched.


1 Answers

This should (also?) do it:

(?!A_)[A-Z](?!((?!/\*).)*\*/)

A short explanation:

(?!A_)[A-Z]     # if no 'A_' can be seen, match any uppercase letter
(?!             # start negative look ahead
  ((?!/\*).)    #   if no '/*' can be seen, match any character (except line breaks)
  *             #   match zero or more of the previous match
  \*/           #   match '*/'
)               # end negative look ahead

So, in plain English:

Match any uppercase except 'A_' and also not an uppercase if '*/' can be seen without first encountering '/*'.

like image 189
Bart Kiers Avatar answered Sep 19 '22 15:09

Bart Kiers