user2483916
user2483916

Reputation: 43

Basic Regular Expression Meaning?

I have this regex:

'/^ANSWER\:(.+?)$/'

I know this roughly translates as:

Strings that begin with "ANSWER:" and...

I'm not exactly sure what the

(.+?)$

translates to? Any help would be greatly appreciated!

Upvotes: 1

Views: 78

Answers (2)

Miles Yucht
Miles Yucht

Reputation: 564

The parenthesized section of the regular expression corresponds to a capturing group, or a part of the regular expression that can be referred to later, so that you can get whatever text fit the sub-regular expression inside the capturing group. The . means to match a single character, and + means at least one instance of, so .+ can be thought of as "at least one of any character." However, the + by itself is "greedy," meaning it matches as many characters as possible, whereas when followed by ?, it is instructed to match "lazily," or as few characters as possible. Because the regular expression ends with $, I think that the ? wouldn't change how the regular expression matched strings, as any match would be forced to match all characters until the end of the line anyways.

Upvotes: 2

Andrew Clark
Andrew Clark

Reputation: 208455

(       # begin capturing group
  .+?     # match any character (.) one or more times (+) as few times as possible (?)
)       # end capturing group
$       # end of string anchor (or end of line anchor, if multiline option is enabled)

The following link has a nice summary of regex syntax:
http://www.regular-expressions.info/reference.html

Upvotes: 7

Related Questions