Reputation: 3707
I am looking for a regular expression to determine when any of the values in a 32-bit hex value is non-zero.
The data patterns look like 0x00000000
and I want to know when any of the digits is non-zero. For example, if 0x00001000
or 0x10000000
or 0xB000000
would be capture by the regular expression, but not a 0x00000000
pattern. Right now I perform a walking pattern match of
0x[^0]
0x0[^0]
0x00[^0]
...
0x0000000[^0]
This will work, but I much rather have one pattern if possible. Thanks.
Mark
Edit: I didn't mention as the RegEx was not needed in a program, otherwise I would have used a different approach, but I was using the RegEx to search for values in a log file using UltraEdit. I could have developed a program or some other means to search, but I was just being lazy, just being honest. Ben S solution worked both in UltraEdit and Rad Software Regular Expression Designer. rampion solution didn't work in either tool, not sure why.
Upvotes: 1
Views: 6692
Reputation: 11
Fixed size hex numbers can be looked up using negative lookahead as:
/(0x(?!0{8})[0-9a-fA-F]{8})/
A group is looked up beginning with 0x
then negative look ahead 0{8}
(fails if found)
otherwise match [0-9a-fA-F]{8}
Works with PCRE, JavaScript, Python. Don't know which editors support negative lookahead.
Upvotes: 1
Reputation: 34120
/0x0{0,7}[^0]/
'0x
', followed by zero to seven '0
', followed by something that is not '0
'
Upvotes: 0
Reputation: 69342
Why not test the hex value against zero? Simpler, faster, more readable.
If a regular expressiong is really necessary, 0x0*[1-9a-fA-F][0-9a-fA-F]*
should do it.
It looks for as many zeros as it can until it finds a non-zero hex value, then gathers the rest of the hex regardless of if it's a zero or not.
Note: this will match any length hex, not just 32 bits.
Upvotes: 5
Reputation: 6721
I think this should cover all cases (if it really has to be a regex):
^0x(?=0*[1-9a-fA-F]0*)[0-9a-fA-F]{8}$
Upvotes: 1
Reputation: 754715
Why not try something slighly different. Testing for a non-zero hex is much harder than testing for a zero hex. So test for zero and manually do the not.
bool IsNonZeroHex(string input) {
return !Regex.IsMatch(input, "^0x(0*)$");
}
Upvotes: 2
Reputation: 89053
/0x0*[1-9a-fA-F][0-9a-fA-F]*/
<atom>*
means match the atom 0 or more times, so this pattern matches the 0x
prefix, followed by 0 or more 0
s, followed by a non-zero hex, followed by some hex.
Upvotes: 2
Reputation: 25665
Surely a simple string compare and if it DOES NOT EQUAL
"0x00000000" you've got your match.
Am I over simplifying it? The is only one FALSE
case, right? When the string is "0x00000000"?
Don't use RegEx unless you have to.
Upvotes: 0