'Regex to match if at least one match is found
I am writing a program for users and their different permissions. One user can have several different permissions, but the problem is that some permissions are mutually exclusive and could cause problems while others are simply unnecessary.
Each user has a string like this:10010111
Each digit represents a specific permission. I have a filter to determine the primary role of an individual which looks like this:1....... or .1.......
Then I have a filter which determine if there are any exclusionary permission errors:..1....1
Finally there is a filter for unnecessary permission errors:...1..1.
Anything not specified by the filters is acceptable and does not need to be checked.
My problem is this: How can I get my regex filters to return something if at least one 1 matches, otherwise return nothing if nothing matches. I have tried by changing my filters to something like this:..1?....1?
But it ends up matching on every single input.
Any ideas, if this is even possible?
Solution 1:[1]
since it is binary, you could just use bitwise operator.
// here is example in javascript
const userPermission = 0b01100110;
const requiredPermission = 0b00100010;
if ((userPermission & requiredPermission) == requiredPermission) {
console.log('this user have permission to do things');
}
this bitwise operator (&) is called AND. this operator will get the same that have 1 value on both binaries.
0110110
0010010
------- &
0010010
0110100
0010010
------- &
0010000
if it is have bits as we wanted, then it should be returns the same as the permission binary. then we just need to check if it equal to the permission .
but, since you are asking using regex instead. then we could just check if this is exact match with /^regexhere$/, and match any else with [01].
00100010 will becomes
/^[01]{2}1[01]{3}1[01]$/
but since binary can have various bits length, you just need to match it from the end, with /regexhere$/.
00100010 will becomes
/1[01]{3}1[01]$/
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
