简体   繁体   English

我如何在php中使用正则表达式验证if语句的语法

[英]How I can validate the syntax of if statement using regex in php

I have a string input, and I want to check if this string contains the correct syntax of if statement. 我有一个字符串输入,我想检查这个字符串是否包含if语句的正确语法。 And extract every part of it. 并提取它的每一部分。

String Format: 字符串格式:

if(D1[Condition]D2)str1:str2

" if " should not be case sensitive if ”不应该区分大小写
D1 And D2 should be numbers D1D2应该是数字
Condition should be one of the following > < >= <= == != 条件应为以下之一> <> = <= ==!=

string examples: 字符串示例:

$example   = "if(54>52)14:0";
$example   = "If(54==52)dsfd:fsde";  

I used this regex but I'm not good at using regex and I don't know if it's good or not. 我使用这个正则表达式,但我不擅长使用正则表达式,我不知道它是否好。

if\(\d+(==|<=|>=|>|<|!=)\d+\).+:.+

I want to extract D1 ,D2 ,Condition , str1 , str2 我想提取D1,D2,Condition,str1,str2

try this! 尝试这个!

^if\((\d+)(>|<|>=|<=|==|!=)(\d+)\)(\w{1,50})\:(\w{1,50})

https://regex101.com/r/qZ7oM7/2 https://regex101.com/r/qZ7oM7/2

This regex should work: 这个正则表达式应该工作:

/^if\(\d+([<>=!]=|[<>])\d+\).{1,50}:.{1,50}$/i

This insensitively matches if( , then digits, then any or your operators, then digits, then ) , then a string of maximum 50 characters, then : , then a string of maximum 50 characters. 这种不敏感地匹配if( ,然后是数字,然后是任何或你的运算符,然后是数字) ,然后是最多50个字符的字符串,然后是: ,然后是最多50个字符的字符串。

Here you have it 在这里你有它

/^If\s*\((\d+)\s*(==|<=|>=|>|<|\!=)\s*(\d+)\)\s*(\w{1,50})\:(\w{1,50})$/i

https://regex101.com/r/jR0bO1/1 https://regex101.com/r/jR0bO1/1

I already added optional spaces in some places which you can add even more before and after other parenthesis. 我已经在某些地方添加了可选空格,您可以在其他括号之前和之后添加更多空格。 \\w doesn't allow spaces in the strings. \\ w不允许字符串中的空格。 You can replace them with . 你可以用它们替换它们。 to allow anything you want 允许任何你想要的东西

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM