Search code examples
regexhaskellpcre

Start of expression in haskell PCRE


I am trying to look for a dollar sign at the start of an expression. I would expect this to be "^\\$", in that I have to escape the dollar sign to avoid it being seen as the end of line. However, I'm seeing the following results:

import Text.Regex.PCRE

let x = "$100.00" :: Text

let m = show x =~ "$" :: Bool
print m

let m = show x =~ "^$" :: Bool
print m

let m = show x =~ "^\\$" :: Bool
print m

Yielding:

True
False
False

What am I missing?

Update 1

If I try escaping to fewer or more "\" characters:

let m = show x =~ "^\$" :: Bool
print m

let m = show x =~ "^\\\$" :: Bool
print m

Both produce

Parse error (line 13, column 30): lexical error in string/character literal at character '$'

Update 2

let y = "1$00.00" :: Text
let m = show y =~ "$" :: Bool
print m
True

Which is why I want ^\\$ rather than just $

Update 3

When I don't use show

let m = x =~ "^\\$" :: Bool
print m

Produces

<interactive>:1:9: error:
    • No instance for (RegexLike Regex Text) arising from a use of ‘=~’
    • In the expression: x =~ "^\\$" :: Bool
      In an equation for ‘m’: m = x =~ "^\\$" :: Bool

Solution

  • Data.Text.unpack is the function that works.

    import Data.Text as T
    
    let x = "$100.00" :: Text
    print $ (T.unpack x)
    print $ IHaskellPrelude.length (T.unpack x)
    let m = ((T.unpack x) =~ "^\\$" :: Bool)
    print m
    

    Produces

    "$100.00"
    7
    True