Go FindStringIndex()

Jmnote (토론 | 기여)님의 2023년 1월 20일 (금) 14:46 판 (→‎개요)
(차이) ← 이전 판 | 최신판 (차이) | 다음 판 → (차이)

1 개요[ | ]

Go FindStringIndex()
Go regexp.FindStringIndex()

2 각행 예시[ | ]

package main

import (
	"fmt"
	"regexp"
)

func main() {
	re := regexp.MustCompile(`ab?`)
	fmt.Println(re.FindStringIndex("tablett"))
	fmt.Println(re.FindStringIndex("foo") == nil)
}
package main

import (
	"fmt"
	"regexp"
)

func main() {
	r, _ := regexp.Compile("p([a-z]+)ch")
	fmt.Println("idx:", r.FindStringIndex("peach punch"))
}

3 여러행 예시[ | ]

package main

import (
	"fmt"
	"regexp"
)

func main() {
	str := `This is a
multiline
string.`
	pattern := `is(.|\n)*str`
	replace := "**REDACTED**"

	// 찾기
	r, _ := regexp.Compile(pattern)
	loc := r.FindStringIndex(str)
	fmt.Println(loc) // [2 23]
	if loc == nil {
		fmt.Println("Cannot find pattern:", pattern)
		return
	}

	// 치환
	result := str[:loc[0]] + replace + str[loc[1]:]
	fmt.Println(result) // Th**REDACTED**ing.
}

4 같이 보기[ | ]

5 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}