简体   繁体   中英

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.

My current expression:

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

pulls in everything after EXAM: , which won't work for this application.

This should do it:

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

Working regex example:

http://regex101.com/r/nD3sQ2

You can use /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...).
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 . match newline on top of everything else.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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