We know that . in a regular express means “any character”. But it is not true when . is in []. A . in [] just means . itself.
If you write \. in a string, the compiler will give you a warning: unknown escape sequence: ‘\.’ [enabled by default]. The \ will be omitted in the string. This behavior is different from php, which keeps both \ and . in the string. So [\.] and [.] is the same.
But [\\.] in QRegExp (i.e., QRegExp(“[\\.] “);) does not mean to match \ OR ., but just to match . because \. is considered as an escape sequence by QRegExp whether it is in [] or not, and that escape sequence means . only. To match \ OR ., you should use QRegExp(“[\\\\\\.] “) or QRegExp(“[\\\\.] “).
Likewise, ? ,*,(,and ) in [] only mean ? and *, etc. themselves, no special meaning. If you cannot remember this rule, just escape them by \, i.e., [\\?\\*] means the same as [?*].
The same rule applies to regular expression in php. In [],*,?,. just mean the literal character itself, no special meaning. If you don’t remember this rule, you can also escape these characters in []. So, preg_replace(“#[\\.\\*\\\\]#”,”-“,$str) and preg_replace(“#[.*\\\\]#”,”-“,$str) have the same effect. Note that you should escape \ in [], otherwise, \ and the following ] will form a escape sequence which means the literal ] itself not the ] with special meaning, so [ will not find the matching ] and php will produce an error. \, whether in [] or not, always keeps its special meaning, i.e., the escape character. If you want a literal \ in [], you should escape it. If the character following the \ can not be escaped such as \p, you will get the error”Warning: preg_replace(): Compilation failed: malformed \P or \p sequence ” . and pre_replace returns a null string(see this post).
For QRegExp, if an un-escapable character follows \, no error occurs, \ will be omitted silently.
Comments are closed, but trackbacks and pingbacks are open.