Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding and replacing the parentheses in a string in Elm 0.16

Tags:

regex

elm

I am currently trying to find the opening parentheses in a string using regex in Elm 0.16 and replace each of them with a parenthesis followed by one space. I also plan to replace each of the closing parentheses in the string with a space followed by a closing parenthesis. This is so I can then replace the spaces with a comma to separate the string. The string I am trying to use the regex on is here:

((data "quoted data" 123 4.5) (data (!@# (4.5) "(more" "data)")))

I have already used regex to remove any backslashes used to escape quotes. For that I used this function:

getRidOfBackslashes : String -> String
getRidOfBackslashes sExpression = 
    sExpression
      |> Regex.replace Regex.All (Regex.regex "\\g") (\_ -> "")

Then I tried to use the following function to achieve the earlier stated goal regarding the opening parentheses:

createSpacesParentheses sExpression =
     sExpression
       |> (\_ -> getRidOfBackslashes sExpression)
       |> Regex.replace Regex.All (Regex.regex "\(") (\_ -> "( ")

Looking at different javascript regex checkers my very simple regex appears to do what I want yet the Elm compiler gives me the error:

(line 1, column 3): unexpected "(" expecting space, "&" or escape code

27│       |> Regex.replace Regex.All (Regex.regex "\(") (\_ -> "( ")
                                                      ^
Maybe <http://elm-lang.org/docs/syntax> can help you figure it out.

I am wondering if I am going about this in the right way and if anyone could offer assistance. Thanks in advance.

like image 983
Thomas Lloyd Avatar asked Sep 25 '22 11:09

Thomas Lloyd


1 Answers

See this reference:

Be careful to escape backslashes properly! For example, "\w" is escaping the letter w which is probably not what you want. You probably want "\\w" instead, which escapes the backslash.

So, the easy way is to just use a character class [(] (as inside a character class, all "special" characters but \, ], ^, and - lose their special meaning) or you may use \\(.

like image 110
Wiktor Stribiżew Avatar answered Oct 13 '22 13:10

Wiktor Stribiżew