regular expression in QRegExp

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.

Did you like this?
Tip admin with Cryptocurrency

Donate Bitcoin to admin

Scan to Donate Bitcoin to admin
Scan the QR code or copy the address below into your wallet to send some bitcoin:

Donate Bitcoin Cash to admin

Scan to Donate Bitcoin Cash to admin
Scan the QR code or copy the address below into your wallet to send bitcoin:

Donate Ethereum to admin

Scan to Donate Ethereum to admin
Scan the QR code or copy the address below into your wallet to send some Ether:

Donate Litecoin to admin

Scan to Donate Litecoin to admin
Scan the QR code or copy the address below into your wallet to send some Litecoin:

Donate Monero to admin

Scan to Donate Monero to admin
Scan the QR code or copy the address below into your wallet to send some Monero:

Donate ZCash to admin

Scan to Donate ZCash to admin
Scan the QR code or copy the address below into your wallet to send some ZCash:
Posted in

Comments are closed, but trackbacks and pingbacks are open.