>  기사  >  백엔드 개발  >  Go 언어는 정규식을 사용하여 웹페이지 텍스트를 추출합니다.

Go 언어는 정규식을 사용하여 웹페이지 텍스트를 추출합니다.

尚
앞으로
2020-01-08 17:47:495154검색

Go 언어는 정규식을 사용하여 웹페이지 텍스트를 추출합니다.

예: 문자열 1000abcd123에서 앞뒤의 두 숫자를 찾으세요.

예 1: 이 문자열 일치의 예

package main
 
import(
    "fmt"
    "regexp"
)
 
var digitsRegexp = regexp.MustCompile(`(\d+)\D+(\d+)`)
 
func main(){
    someString:="1000abcd123"
    fmt.Println(digitsRegexp.FindStringSubmatch(someString))
}

위 코드 출력:

[1000abcd123 1000 123]

예 2: 명명된 정규 표현식 사용

package main
 
import(
    "fmt"
    "regexp"
)
 
var myExp=regexp.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)
 
func main(){
    fmt.Printf("%+v",myExp.FindStringSubmatch("1234.5678.9"))
}

위 코드 출력, 모든 일치 항목이 출력됨:

[1234.5678.9 1234 5678 9]

The Named 여기서 정규 표현식의 이름을 지정하는 그룹 캡처(?P) 방법은 Python 및 Go 언어에 고유하며, java 및 C#은 (?) 이름 지정 방법입니다.

예 3: 모든 이름 지정 정보를 가져와 사용하는 메서드로 정규식 클래스를 확장합니다.

package main
 
import(
    "fmt"
    "regexp"
)
 
//embed regexp.Regexp in a new type so we can extend it
type myRegexp struct{ 
    *regexp.Regexp
}
 
//add a new method to our new regular expression type
func(r *myRegexp)FindStringSubmatchMap(s string) map[string]string{
    captures:=make(map[string]string)
 
    match:=r.FindStringSubmatch(s)
    if match==nil{
        return captures
    }
 
    for i,name:=range r.SubexpNames(){
        //Ignore the whole regexp match and unnamed groups
        if i==0||name==""{
            continue
        }
 
        captures[name]=match[i]
 
    }
    return captures
}
 
//an example regular expression
var myExp=myRegexp{regexp.MustCompile(`(?P<first>\d+)\.(\d+).(?P<second>\d+)`)}
 
func main(){
    mmap:=myExp.FindStringSubmatchMap("1234.5678.9")
    ww:=mmap["first"]
    fmt.Println(mmap)
    fmt.Println(ww)
}


위 코드의 출력:

map[first:1234 second:9]

1234

예제 4, 번호 제한 정보를 가져와 지도에 기록합니다.

package main
 
import(
    "fmt"
    iconv "github.com/djimenez/iconv-go"
    "io/ioutil"
    "net/http"
    "os"
    "regexp"
)
 
// embed regexp.Regexp in a new type so we can extend it
type myRegexp struct{
    *regexp.Regexp
}
 
// add a new method to our new regular expression type
func(r *myRegexp)FindStringSubmatchMap(s string)[](map[string]string){
    captures:=make([](map[string]string),0)
 
    matches:=r.FindAllStringSubmatch(s,-1)
 
    if matches==nil{
        return captures
    }
 
    names:=r.SubexpNames()
 
    for _,match:=range matches{
 
        cmap:=make(map[string]string)
 
        for pos,val:=range match{
            name:=names[pos]
            if name==""{
                continue
            }
 
            /*
                fmt.Println("+++++++++")
                fmt.Println(name)
                fmt.Println(val)
            */
            cmap[name]=val
        }
 
        captures=append(captures,cmap)
 
    }
 
    return captures
}
 
// 抓取限号信息的正则表达式
var myExp=myRegexp{regexp.MustCompile(`自(?P<byear>[\d]{4})年(?P<bmonth>[\d]{1,2})月(?P<bday>[\d]{1,2})日至(?P<eyear>[\d]{4})年(?P<emonth>[\d]{1,2})月(?P<eday>[\d]{1,2})日,星期一至星期五限行机动车车牌尾号分别为:(?P<n11>[\d])和(?P<n12>[\d])、(?P<n21>[\d])和(?P<n22>[\d])、(?P<n31>[\d])和(?P<n32>[\d])、(?P<n41>[\d])和(?P<n42>[\d])、(?P<n51>[\d])和(?P<n52>[\d])`)}
 
func ErrorAndExit(err error){
    fmt.Fprintln(os.Stderr,err)
    os.Exit(1)
}
 
func main(){
    response,err:=http.Get("http://www.bjjtgl.gov.cn/zhuanti/10weihao/index.html")
    defer response.Body.Close()
 
    if err!=nil{
        ErrorAndExit(err)
    }
 
    input,err:=ioutil.ReadAll(response.Body)
    if err!=nil{
        ErrorAndExit(err)
    }
    body :=make([]byte,len(input))
    iconv.Convert(input,body,"gb2312","utf-8")
 
    mmap:=myExp.FindStringSubmatchMap(string(body))
 
    fmt.Println(mmap)
}

위 코드 출력:

[map[n32:0 n22:9 emonth:7 n11:3 n41:1 n21:4 n52:7 bmonth:4 n51:2 bday:9 n42:6 byear:2012 eday:7 eyear:2012 n12:8 n31:5]
map[emonth:10 n41:5 n52:6 n31:4 byear:2012 n51:1 eyear:2012 n32:9 bmonth:7 n22:8 bday:8 n11:2 eday:6 n42:0 n21:3 n12:7]
map[bday:7 n51:5 n22:7 n31:3 eday:5 n32:8 byear:2012 bmonth:10 emonth:1 eyear:2013 n11:1 n12:6 n52:0 n21:2 n42:9 n41:4]
map[eyear:2013 byear:2013 n22:6 eday:10 bmonth:1 n41:3 n32:7 n31:2 n21:1 n11:5 bday:6 n12:0 n51:4 n42:8 emonth:4 n52:9]]

더 많은 Go 언어 지식을 보려면 PHP 중국어 웹사이트 go 언어 튜토리얼 칼럼을 주목하세요.

위 내용은 Go 언어는 정규식을 사용하여 웹페이지 텍스트를 추출합니다.의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
이 기사는 cnblogs.com에서 복제됩니다. 침해가 있는 경우 admin@php.cn으로 문의하시기 바랍니다. 삭제