Manish Garg
Manish Garg

Reputation: 89

RegEx match is not working if it contains $

The following match returns false. How can I change the regular expression to correct it?

"hello$world" -match '^hello$(wo|ab).*$' 

"hello$abcde" -match '^hello$(wo|ab).*$'

Upvotes: 1

Views: 781

Answers (1)

Doug Richardson
Doug Richardson

Reputation: 10821

'hello$world' -match '^hello\$(wo|ab).*$'
'hello$abcde' -match '^hello\$(wo|ab).*$'

You need to quote the left hand side with single quotes so $world isn't treated like variable interpolation. You need to escape the $ in the right hand side so it isn't treated as end of line.

From About Quoting Rules:

When you enclose a string in double quotation marks (a double-quoted string), variable names that are preceded by a dollar sign ($) are replaced with the variable's value before the string is passed to the command for processing.

...

When you enclose a string in single-quotation marks (a single-quoted string), the string is passed to the command exactly as you type it. No substitution is performed.

From About Regular Expressions:

The two commonly used anchors are ^ and $. The carat ^ matches the start of a string, and $, which matches the end of a string. This allows you to match your text at a specific position while also discarding unwanted characters.

...

Escaping characters

The backslash \ is used to escape characters so they are not parsed by the regular expression engine.

The following characters are reserved: []().\^$|?*+{}.

You will need to escape these characters in your patterns to match them in your input strings.

Upvotes: 3

Related Questions