regex - "Unknown escape sequence" error in Go -


i have following function written in go. idea function has string passed , returns first ipv4 ip address found. if no ip address found, empty string returned.

func parseip(checkipbody string) string {     reg, err := regexp.compile("[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+")     if err == nil {         return ""     }        return reg.findstring(checkipbody) } 

the compile-time error i'm getting is

unknown escape sequence: .

how can tell go '.' actual character i'm looking for? thought escaping trick, apparently i'm wrong.

the \ backslash isn't being interpreted regex parser, it's being interpreted in string literal. should escape backslash again:

regexp.compile("[0-9]+\\.[0-9]+\\.[0-9]+\\.[0-9]+") 

a string quoted " double-quote characters known "interpreted string literal" in go. interpreted string literals string literals in languages: \ backslash characters aren't included literally, they're used give special meaning next character. source must included \\ 2 backslashes in row obtain single backslash character in parsed value.

as evan shaw pointed out in comments, go has alternative can useful when writing string literals regular expressions. "raw string literal" quoted ` backtick characters. there no special characters in raw string literal, long pattern doesn't include backtick can use syntax without escaping anything:

regexp.compile(`[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+`) 

this described in the "string literals" section of go spec.


Comments

Popular posts from this blog

linux - Using a Cron Job to check if my mod_wsgi / apache server is running and restart -

actionscript 3 - TweenLite does not work with object -

jQuery Ajax Render Fragments OR Whole Page -