"Go FindStringIndex()"의 두 판 사이의 차이

 
3번째 줄: 3번째 줄:
;Go regexp.FindStringIndex()
;Go regexp.FindStringIndex()


==각행 예시==
<syntaxhighlight lang='go' run>
<syntaxhighlight lang='go' run>
package main
package main
28번째 줄: 29번째 줄:
r, _ := regexp.Compile("p([a-z]+)ch")
r, _ := regexp.Compile("p([a-z]+)ch")
fmt.Println("idx:", r.FindStringIndex("peach punch"))
fmt.Println("idx:", r.FindStringIndex("peach punch"))
}
</syntaxhighlight>
==여러행 예시==
<syntaxhighlight lang='go' run>
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.
}
}
</syntaxhighlight>
</syntaxhighlight>

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 }}