douji1077 2010-05-26 14:01
浏览 229

Php和python正则表达式的区别?

I need to parse a string 'Open URN: 100000 LA: ' and get 100000 from it. on python regexp (?<=Open URN: )[0-9]+(?= LA:) works fine but in php it gives following error:

preg_match(): Unknown modifier '['

I need it working php, so please help me to solve this problem and tell about difference in python and php regexps.

  • 写回答

2条回答 默认 最新

  • dpchen2004 2010-05-26 14:05
    关注

    You have to use delimiters when you are using the Perl Compatible Regular Expressions (PCRE) functions in PHP (to which preg_match() belongs).

    From the documentation:

    When using the PCRE functions, it is required that the pattern is enclosed by delimiters. A delimiter can be any non-alphanumeric, non-backslash, non-whitespace character.

    The reason for using delimiters is that you can add pattern modifiers after the last delimiter, e.g. to make an case-insensitive match:

    #[a-z]#i  // # is the delimiter.
    

    Back to your problem:

    In your case, PHP thinks the brackets () are your delimiters (yes, opening and closing brackets are valid delimiters, see the documentation) and ?<=Open URN: is your pattern . Then it encounters [ and treats it as pattern modifier, but it is not a valid one.

    Your pattern with delimiter %:

    preg_match('%(?<=Open URN: )[0-9]+(?= LA:)%', 'Open URN: 100000 LA: ');
    

    There are a lot examples in the documentation of preg_match()


    Python vs PHP

    The only thing I found regarding regular expressions in Python is, that Perl syntax is used but I don't know if the full syntax is supported.
    As already mentioned, PHP uses PCRE. Description of the differences between PCRE and Perl regex.

    评论

报告相同问题?

悬赏问题

  • ¥15 乘性高斯噪声在深度学习网络中的应用
  • ¥15 运筹学排序问题中的在线排序
  • ¥15 关于docker部署flink集成hadoop的yarn,请教个问题 flink启动yarn-session.sh连不上hadoop,这个整了好几天一直不行,求帮忙看一下怎么解决
  • ¥30 求一段fortran代码用IVF编译运行的结果
  • ¥15 深度学习根据CNN网络模型,搭建BP模型并训练MNIST数据集
  • ¥15 C++ 头文件/宏冲突问题解决
  • ¥15 用comsol模拟大气湍流通过底部加热(温度不同)的腔体
  • ¥50 安卓adb backup备份子用户应用数据失败
  • ¥20 有人能用聚类分析帮我分析一下文本内容嘛
  • ¥30 python代码,帮调试,帮帮忙吧