ithisa
ithisa

Reputation: 790

Why does this regex not work for matching C integer declarations?

I'm using the following regular expression to match C integer declarations without initialization. The integer might be unsigned:

^(unsigned[[:space:]]+|^$)int[[:space:]]+[a-zA-Z0-9_]+;$

The first part matches unsigned followed by a number of spaces, or nothing. The second part matches int followed by spaces, plus a variable name and a semicolon.

Unfortunately, this seems to not match any integer declaration that doesn't have unsigned in it. What am I doing wrong? Does ^$ in a (...|...) pattern do what I expect (match the empty string)? Google and my regex manual isn't helping.

Upvotes: 0

Views: 219

Answers (1)

Barmar
Barmar

Reputation: 782130

Try this:

^[[:space:]]*(unsigned[[:space:]]+)?int[[:space:]]+[a-zA-Z0-9_]+;[[:space:]]*$

To make a group optional, put ? after it. ^$ doesn't match an empty string in the middle of a match, it matches an entirely empty string -- ^ matches the beginning of the string, and $ matches the end of the string.

Upvotes: 2

Related Questions