doukang2003 2016-09-26 10:58
浏览 42
已采纳

使用preg_match验证表达式

Good day! I'm trying to create a program that accepts a Lambda expression from the user and what this program does is to check if it is a Valid Lambda expression.

example - user inputs (λa.abc)a -> then validates

my problem is that my knowledge of Regex function is very limited, I've been using preg_match to solve this but still not much of a progress. any help will be much appreciated.. Thanks :)

Well these are the rules of a valid λ-expression

  1. a single variable = (single letter)
  2. function application = (λ-expression)(λ-expression)
  3. function abstraction = λ(variable).(λ-expression)

This is the code I did with preg_match

if(preg_match("/\((L([a-z])*.(([a-z])*)*)\)/", $getexpression, $match)):
print "Valid!";

does not really work that well

  • 写回答

1条回答 默认 最新

  • doudun8705 2016-09-26 13:11
    关注

    I must confess that I didn't get too much from your definition of the expressions, since you basically said "an expression is a variable, or a collection of variables".
    I'd generally recommend avoiding using the word you're trying to define within the definition itself.

    That said, from reading up on Wikipedia and the comments, I think I might have gotten to what could be construed as a working regular expression for this:

    // Basic definition: Lambda + letter == variable.
    $lVar = 'λ[a-z]';
    
    // Complex definition: Variable, possibly followed by variables,
    // and closed with a letter preceeded by a dot or whitespace.
    $lExp = "({$lVar}(?:\\.{$lVar})*(?:[ .][a-z]+))";
    
    // Complete definition:
    //    1. Only single  expression.
    //    2. Or a parameterized expression which may contain
    //       the entire pattern recursively.
    $lRegEx = "/^$lExp|\\($lExp(?R)\\)\\Z/u";
    

    That being said, I'm not 100% sure this can be tested with a regular expression. At least not fully. This seems to be the sort of thing that you need to write/use a tokenizer for.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示
  • ¥15 求三国群英传pl国战时间的修改方法
  • ¥15 matlab代码代写,需写出详细代码,代价私
  • ¥15 ROS系统搭建请教(跨境电商用途)