简体   繁体   English

可以在正则表达式匹配中使用$ 1吗?

[英]Is it possible to use $1 in a regex match?

I'm creating a text parser, that basically looks for the following: 我正在创建一个文本解析器,它基本上会查找以下内容:

{IF SOMETHING} then include this text {ENDIF SOMETHING}

I can find that by using the regex: 我可以使用正则表达式找到它:

/{IF [A-Z]+}.*{ENDIF [A-Z]}/

But that wont help if there are nested conditions. 但是,如果存在嵌套条件,那将无济于事。 So i was looking to do something more like: 所以我想做更多的事情:

/{IF ([A-Z]+)}.*{ENDIF $1}/

But that doesn't seem to work - is it possible? 但这似乎不起作用-可能吗?

You can use this other syntax too: \\g{1} that is useful to avoid confusion with a backreference followed with a literal digit. 您也可以使用以下其他语法: \\g{1} ,它可以避免与后向引用后跟原义数字的混淆。 This syntax allows to use relative references like this: \\g{-1} (ie the last defined capture group on the left) 该语法允许使用如下相对引用: \\g{-1} (即,左侧最后定义的捕获组)

$1 is only used in a replacement string with preg_replace . $1仅在使用preg_replace的替换字符串中使用。

PHP Regex uses \\1 instead of $1. PHP Regex使用\\ 1而不是$ 1。 For more information, refer to the PHP Manual on regex back references. 有关更多信息,请参考regex back引用上的PHP手册

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

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