Reputation: 1820
I would like to ask if there is any logic behind this regex:
([\d^5]{1})
It maps all digits, but shouldn't it be ignoring 5?
I know that when I want to ignore 5 I can use this regex:
([^\D5]{1})
However I am curious if there is any logic behind using negation operator in the middle of grouping or it should be used always at the beginning.
Upvotes: 0
Views: 48
Reputation: 30995
There are some regex engines that supports character class intersections. For instance you could use:
[\d&&[^5]]
The syntax is:
[class&&[intersect]]
Quoting regex-expresion.info
Character class intersection is supported by Java, JGsoft V2, and by Ruby 1.9 and later. It makes it easy to match any single character that must be present in two sets of characters. The syntax for this is [class&&[intersect]]. You can use the full character class syntax within the intersected character class.
If the intersected class does not need a negating caret, then Java and Ruby allow you to omit the nested square brackets: [class&&intersect].
Anyway, most engines does not have this logic, so when you have to negate a character class you have to use the syntax [^...]
, but you can't change the ^
to exclude some characters and allow others, you would need to extend your regex and not use shortcuts.
Upvotes: 0
Reputation: 468
Since I can't comment (Not enough rep). Give the following a try
([0-46-9])
usually for negation you need the ^ after the [, so a regex to ignore 5's would look like
[^5]
as for your queries you're asking regex to match a digit, then afterwards the beginning of the line, then a 5. ^ outside of [] denote the beginning of a line/string.
Take the above with a grain of salt, I'm not new to regex, but i'm not really that strong with negations.
Upvotes: 1