简体   繁体   English

匹配单词,然后在带有正则表达式的PHP中分隔符之间

[英]Matching Word, then between delimiters in PHP With Regular Expression

Having a bit of a difficult time working out a regular expression that will do what I need. 在编写正则表达式时遇到一些困难,它将满足我的需求。 Basically, I am parsing through a file with several thousand lines of text, and looking for anything with the line: 基本上,我通过一个包含数千行文本的文件进行解析,并用该行查找任何内容:

EXAM: 考试:

Matched text will always be in the format: 匹配的文本将始终采用以下格式:

EXAM: (teststring) extra text 考试:(测试字符串)多余的文字

So what I am trying to do is match on EXAM: , then pull in everything within the parenthesis. 所以我想做的是在EXAM:上进行匹配,然后插入括号内的所有内容。

My current expression: 我目前的表情:

/^.+?\EXAM:(.+)$/is 

pulls in everything after EXAM: , which won't work for this application. 在EXAM:之后插入所有内容,该功能不适用于此应用程序。

This should do it: 应该这样做:

(?<=EXAM: \()([^)]+)

Working regex example: 工作正则表达式示例:

http://regex101.com/r/nD3sQ2 http://regex101.com/r/nD3sQ2

You can use /EXAM:\\s*\\(([^)]+)\\)/i : 您可以使用/EXAM:\\s*\\(([^)]+)\\)/i

if(preg_match("/EXAM:\s*\(([^)]+)\)/i", $thisline, $matches)) {
    $exam_type = trim($matches[1]);
}

[^)] will match anything except a closing parenthesis, and it will stop at the first ) encountered. [^)]将匹配除右括号以外的所有内容,并且会在遇到的第一个)处停止。 You need to escape parenthesis as they are special regex characters (they are used to capture variables). 您需要对括号进行转义,因为它们是特殊的正则表达式字符(它们用于捕获变量)。 Here for example you use the unescaped ones to store what you want. 例如,在这里您使用未转义的来存储所需的内容。
\\s is a shortcut for any type of whitespace (space, tab...). \\s是任何类型的空格(空格,制表符...)的快捷方式。
You probably don't need the s at the end since you are parsing the doc line by line: the s flag only makes the . 您可能不需要在末尾加上s ,因为您是逐行解析doc: s标志仅使成为. match newline on top of everything else. 在所有其他内容上匹配换行符。

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

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