Decide a C integer literal
Retina 0.8.2, 60 59 bytes
i`^(0[0-7]*|0x[\da-f]+|[1-9]\d*)(u)?(l)?(?-i:\3?)(?(2)|u?)$
Try it online! Link includes test cases. Edit: Saved 1 byte thanks to @FryAmTheEggMan. Explanation:
i`
Match case-insensitively.
^(0[0-7]*|0x[\da-f]+|[1-9]\d*)
Start with either octal, hex or decimal.
(u)?
Optional unsigned specifier.
(l)?
Optional length specifier.
(?-i:\3?)
Optionally repeat the length specifier case sensitively.
(?(2)|u?)$
If no unsigned specifier yet, then another chance for an optional specifier, before the end of the literal.
Perl 5 -p
, 65 61 bytes
@NahuelFouilleul shaved 4 bytes
$_=/^(0[0-7]*|0x\p{Hex}+|[1-9]\d*)(u?l?l?|l?l?u?)$/i*!/lL|Ll/
Try it online!
Java 8 / Scala polyglot, 89 79 bytes
s->s.matches("(?!.*(Ll|lL))(?i)(0[0-7]*|[1-9]\\d*|0x[\\da-f]+)(u?l?l?|l?l?u?)")
-10 bytes thanks to @NahuelFouilleul
Try it online in Java 8.
Try it online in Scala (except with =>
instead of ->
- thanks to @TomerShetah).
Explanation:
s-> // Method with String parameter and boolean return-type
s.matches( // Check whether the input-string matches the regex
"(?!.*(Ll|lL))(?i)(0[0-7]*|[1-9]\\d*|0x[\\da-f]+)(u?l?l?|l?l?u?)")
Regex explanation:
In Java, the String#matches
method implicitly adds a leading and trailing ^...$
to match the entire string, so the regex is:
^(?!.*(Ll|lL))(?i)(0[0-7]*|[1-9]\d*|0x[\da-f]+)(u?l?l?|l?l?u?)$
(?! ) # The string should NOT match:
^ .* # Any amount of leading characters
( ) # Followed by:
Ll # "Ll"
|lL # Or "lL"
# (Since the `?!` is a negative lookahead, it acts loose from the
# rest of the regex below)
(?i) # Using case-insensitivity,
^ ( # the string should start with:
0 # A 0
[0-7]* # Followed by zero or more digits in the range [0,7]
| # OR:
[1-9] # A digit in the range [1,9]
\d* # Followed by zero or more digits
| # OR:
0x # A "0x"
[ ]+ # Followed by one or more of:
\d # Digits
a-f # Or letters in the range ['a','f']
)( # And with nothing in between,
)$ # the string should end with:
u? # An optional "u"
l?l? # Followed by no, one, or two "l"
| # OR:
l?l? # No, one, or two "l"
u? # Followed by an optional "u"