Reputation: 34884
I want to capture a group in as string:
import Text.Regex.Posix
"somestring; somestring2=\"(.*?)\"" =~ "somestring; somestring2=\"my_super_string123\"" :: String
It returns an empty string ""
, as opposed to my_super_string123
which I expect. I've tried ::[String]
and ::[[String]]
and, obviously, they were empty. Your suggestions?
Upvotes: 0
Views: 198
Reputation: 54058
The problem is that you have your string and your pattern swapped. You also will want to have the return type be [[String]]
:
> "somestring; somestring2=\"my_super_string123\"" =~ "somestring; somestring2=\"(.*)\"" :: [[String]]
[["somestring; somestring2=\"my_super_string123\"", "my_super_string123"]]
Note that I had to remove the ?
from the .*?
part of the pattern. This is because POSIX doesn't support the lazy quantifier *?
. You'll have to select both of the POSIX flavors from the drop downs to see, but it says both do not support the lazy quantifiers. It's also recommended to use negation instead of laziness for regex since it improves performance over having to backtrack. To do this, you'd have to change your pattern to
"somestring; somestring2=\"([^\"]*)\""
To clarify, here's the output from my GHCi:
> "s1; s2=\"my_super_string123\"" =~ "s1; s2=\"([^\"]*)\"" :: [[String]]
[["s1; s2=\"my_super_string123\"","my_super_string123"]]
it :: [[String]]
> "s1; s2=\"my_super_string123\"" =~ "s1; s2=\"([^\"]*)\"" :: String
"s1; s2=\"my_super_string123\""
it :: String
1As you can see, with the return type as String
, it returns whatever text matches the entire pattern, not just the capturing groups. Use [[String]]
when you want to get the contents of the individual capturing groups.
Upvotes: 2