[英]What is a regular expression for matching numbers divisible by 4?
I want to make a lexical analyzer that detects numbers divisible by 4. 我想做一个词法分析器来检测被4整除的数字。
Sample code - 示例代码-
%%
16(divisible by 4) {printf("divisible by 4 %s\n",yytext);}
%%
main()
{
yylex();
}
The single-digit numbers which are divisible by 4 are 0, 4, and 8. 可被4整除的一位数字是0、4和8。
The two-digit numbers which are divisible by 4 can be divided into two groups: 可被4整除的两位数字可以分为两组:
12, 16, 32, 36, 52, 56, 72, 76, 92, 96
20, 24, 28, 40, 44, 48, 60, 64, 68, 80, 84, 88
Any number which is three or more digits and ends in any of these two-digit numbers is divisible by four. 任何三位数或更多位数并且以这些两位数结尾的数字都可以被四整除。
Therefore, the regular expression should search for numbers of the form \\d*[02468][048]
, or the form \\d*[13579][26]
, or the single digit numbers 0
, 4
, and 8
. 因此,正则表达式应搜索的形式的数字
\\d*[02468][048]
或形式\\d*[13579][26]
或单位数字0
, 4
,和8
。
This regular expression matches all numbers, positive or negative, which are divisible by 4: 此正则表达式匹配所有可被4整除的正数或负数:
-?(?:\d*[02468][048]|\d*[13579][26]|[048])
Note that this could match part of a number, such as 24
in 1245
. 请注意,这可以匹配数字的一部分,例如
1245
24
。 If you want to make sure that you only match an entire number, you could add negative look-around expressions: 如果要确保只匹配一个整数,则可以添加否定的环顾四周表达式:
(?<!\d)-?(?:\d*[02468][048]|\d*[13579][26]|[048])(?!\d)
or you could use word boundaries: 或者您可以使用单词边界:
\b-?(?:\d*[02468][048]|\d*[13579][26]|[048])\b
%%
[0-9]+ {int number = atoi(yytext); if((number % 4) == 0) printf("Div_4 %d\n", number);}
%%
main()
{
yylex();
}
As lex/flex
support C, so you can save the string as integer and then check it in C. 由于
lex/flex
支持C,因此您可以将字符串另存为整数,然后在C中进行检查。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.