github.com/shogo82148/std@v1.22.1-0.20240327122250-4e474527810c/regexp/example_test.go (about) 1 // Copyright 2013 The Go Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 package regexp_test 6 7 import ( 8 "github.com/shogo82148/std/fmt" 9 "github.com/shogo82148/std/regexp" 10 "github.com/shogo82148/std/strings" 11 ) 12 13 func Example() { 14 // 式を一度だけコンパイルする。通常は初期化時に行う。 15 // バックスラッシュを引用符で囲まないために、生文字列を使用する。 16 var validID = regexp.MustCompile(`^[a-z]+\[[0-9]+\]$`) 17 18 fmt.Println(validID.MatchString("adam[23]")) 19 fmt.Println(validID.MatchString("eve[7]")) 20 fmt.Println(validID.MatchString("Job[48]")) 21 fmt.Println(validID.MatchString("snakey")) 22 // Output: 23 // true 24 // true 25 // false 26 // false 27 } 28 29 func ExampleMatch() { 30 matched, err := regexp.Match(`foo.*`, []byte(`seafood`)) 31 fmt.Println(matched, err) 32 matched, err = regexp.Match(`bar.*`, []byte(`seafood`)) 33 fmt.Println(matched, err) 34 matched, err = regexp.Match(`a(b`, []byte(`seafood`)) 35 fmt.Println(matched, err) 36 37 // Output: 38 // true <nil> 39 // false <nil> 40 // false error parsing regexp: missing closing ): `a(b` 41 } 42 43 func ExampleMatchString() { 44 matched, err := regexp.MatchString(`foo.*`, "seafood") 45 fmt.Println(matched, err) 46 matched, err = regexp.MatchString(`bar.*`, "seafood") 47 fmt.Println(matched, err) 48 matched, err = regexp.MatchString(`a(b`, "seafood") 49 fmt.Println(matched, err) 50 // Output: 51 // true <nil> 52 // false <nil> 53 // false error parsing regexp: missing closing ): `a(b` 54 } 55 56 func ExampleQuoteMeta() { 57 fmt.Println(regexp.QuoteMeta(`Escaping symbols like: .+*?()|[]{}^$`)) 58 // Output: 59 // Escaping symbols like: \.\+\*\?\(\)\|\[\]\{\}\^\$ 60 } 61 62 func ExampleRegexp_Find() { 63 re := regexp.MustCompile(`foo.?`) 64 fmt.Printf("%q\n", re.Find([]byte(`seafood fool`))) 65 66 // Output: 67 // "food" 68 } 69 70 func ExampleRegexp_FindAll() { 71 re := regexp.MustCompile(`foo.?`) 72 fmt.Printf("%q\n", re.FindAll([]byte(`seafood fool`), -1)) 73 74 // Output: 75 // ["food" "fool"] 76 } 77 78 func ExampleRegexp_FindAllSubmatch() { 79 re := regexp.MustCompile(`foo(.?)`) 80 fmt.Printf("%q\n", re.FindAllSubmatch([]byte(`seafood fool`), -1)) 81 82 // Output: 83 // [["food" "d"] ["fool" "l"]] 84 } 85 86 func ExampleRegexp_FindSubmatch() { 87 re := regexp.MustCompile(`foo(.?)`) 88 fmt.Printf("%q\n", re.FindSubmatch([]byte(`seafood fool`))) 89 90 // Output: 91 // ["food" "d"] 92 } 93 94 func ExampleRegexp_Match() { 95 re := regexp.MustCompile(`foo.?`) 96 fmt.Println(re.Match([]byte(`seafood fool`))) 97 fmt.Println(re.Match([]byte(`something else`))) 98 99 // Output: 100 // true 101 // false 102 } 103 104 func ExampleRegexp_FindString() { 105 re := regexp.MustCompile(`foo.?`) 106 fmt.Printf("%q\n", re.FindString("seafood fool")) 107 fmt.Printf("%q\n", re.FindString("meat")) 108 // Output: 109 // "food" 110 // "" 111 } 112 113 func ExampleRegexp_FindStringIndex() { 114 re := regexp.MustCompile(`ab?`) 115 fmt.Println(re.FindStringIndex("tablett")) 116 fmt.Println(re.FindStringIndex("foo") == nil) 117 // Output: 118 // [1 3] 119 // true 120 } 121 122 func ExampleRegexp_FindStringSubmatch() { 123 re := regexp.MustCompile(`a(x*)b(y|z)c`) 124 fmt.Printf("%q\n", re.FindStringSubmatch("-axxxbyc-")) 125 fmt.Printf("%q\n", re.FindStringSubmatch("-abzc-")) 126 // Output: 127 // ["axxxbyc" "xxx" "y"] 128 // ["abzc" "" "z"] 129 } 130 131 func ExampleRegexp_FindAllString() { 132 re := regexp.MustCompile(`a.`) 133 fmt.Println(re.FindAllString("paranormal", -1)) 134 fmt.Println(re.FindAllString("paranormal", 2)) 135 fmt.Println(re.FindAllString("graal", -1)) 136 fmt.Println(re.FindAllString("none", -1)) 137 // Output: 138 // [ar an al] 139 // [ar an] 140 // [aa] 141 // [] 142 } 143 144 func ExampleRegexp_FindAllStringSubmatch() { 145 re := regexp.MustCompile(`a(x*)b`) 146 fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-", -1)) 147 fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-", -1)) 148 fmt.Printf("%q\n", re.FindAllStringSubmatch("-ab-axb-", -1)) 149 fmt.Printf("%q\n", re.FindAllStringSubmatch("-axxb-ab-", -1)) 150 // Output: 151 // [["ab" ""]] 152 // [["axxb" "xx"]] 153 // [["ab" ""] ["axb" "x"]] 154 // [["axxb" "xx"] ["ab" ""]] 155 } 156 157 func ExampleRegexp_FindAllStringSubmatchIndex() { 158 re := regexp.MustCompile(`a(x*)b`) 159 // インデックス: 160 // 01234567 012345678 161 // -ab-axb- -axxb-ab- 162 fmt.Println(re.FindAllStringSubmatchIndex("-ab-", -1)) 163 fmt.Println(re.FindAllStringSubmatchIndex("-axxb-", -1)) 164 fmt.Println(re.FindAllStringSubmatchIndex("-ab-axb-", -1)) 165 fmt.Println(re.FindAllStringSubmatchIndex("-axxb-ab-", -1)) 166 fmt.Println(re.FindAllStringSubmatchIndex("-foo-", -1)) 167 // Output: 168 // [[1 3 2 2]] 169 // [[1 5 2 4]] 170 // [[1 3 2 2] [4 7 5 6]] 171 // [[1 5 2 4] [6 8 7 7]] 172 // [] 173 } 174 175 func ExampleRegexp_FindSubmatchIndex() { 176 re := regexp.MustCompile(`a(x*)b`) 177 178 // インデックス: 179 // 01234567 012345678 180 // -ab-axb- -axxb-ab- 181 fmt.Println(re.FindSubmatchIndex([]byte("-ab-"))) 182 fmt.Println(re.FindSubmatchIndex([]byte("-axxb-"))) 183 fmt.Println(re.FindSubmatchIndex([]byte("-ab-axb-"))) 184 fmt.Println(re.FindSubmatchIndex([]byte("-axxb-ab-"))) 185 fmt.Println(re.FindSubmatchIndex([]byte("-foo-"))) 186 // Output: 187 // [1 3 2 2] 188 // [1 5 2 4] 189 // [1 3 2 2] 190 // [1 5 2 4] 191 // [] 192 } 193 194 func ExampleRegexp_Longest() { 195 re := regexp.MustCompile(`a(|b)`) 196 fmt.Println(re.FindString("ab")) 197 re.Longest() 198 fmt.Println(re.FindString("ab")) 199 // Output: 200 // a 201 // ab 202 } 203 204 func ExampleRegexp_MatchString() { 205 re := regexp.MustCompile(`(gopher){2}`) 206 fmt.Println(re.MatchString("gopher")) 207 fmt.Println(re.MatchString("gophergopher")) 208 fmt.Println(re.MatchString("gophergophergopher")) 209 // Output: 210 // false 211 // true 212 // true 213 } 214 215 func ExampleRegexp_NumSubexp() { 216 re0 := regexp.MustCompile(`a.`) 217 fmt.Printf("%d\n", re0.NumSubexp()) 218 219 re := regexp.MustCompile(`(.*)((a)b)(.*)a`) 220 fmt.Println(re.NumSubexp()) 221 // Output: 222 // 0 223 // 4 224 } 225 226 func ExampleRegexp_ReplaceAll() { 227 re := regexp.MustCompile(`a(x*)b`) 228 fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("T"))) 229 fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1"))) 230 fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W"))) 231 fmt.Printf("%s\n", re.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W"))) 232 233 re2 := regexp.MustCompile(`a(?P<1W>x*)b`) 234 fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("$1W"))) 235 fmt.Printf("%s\n", re2.ReplaceAll([]byte("-ab-axxb-"), []byte("${1}W"))) 236 237 // Output: 238 // -T-T- 239 // --xx- 240 // --- 241 // -W-xxW- 242 // --xx- 243 // -W-xxW- 244 } 245 246 func ExampleRegexp_ReplaceAllLiteralString() { 247 re := regexp.MustCompile(`a(x*)b`) 248 fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "T")) 249 fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "$1")) 250 fmt.Println(re.ReplaceAllLiteralString("-ab-axxb-", "${1}")) 251 // Output: 252 // -T-T- 253 // -$1-$1- 254 // -${1}-${1}- 255 } 256 257 func ExampleRegexp_ReplaceAllString() { 258 re := regexp.MustCompile(`a(x*)b`) 259 fmt.Println(re.ReplaceAllString("-ab-axxb-", "T")) 260 fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1")) 261 fmt.Println(re.ReplaceAllString("-ab-axxb-", "$1W")) 262 fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W")) 263 264 re2 := regexp.MustCompile(`a(?P<1W>x*)b`) 265 fmt.Printf("%s\n", re2.ReplaceAllString("-ab-axxb-", "$1W")) 266 fmt.Println(re.ReplaceAllString("-ab-axxb-", "${1}W")) 267 268 // Output: 269 // -T-T- 270 // --xx- 271 // --- 272 // -W-xxW- 273 // --xx- 274 // -W-xxW- 275 } 276 277 func ExampleRegexp_ReplaceAllStringFunc() { 278 re := regexp.MustCompile(`[^aeiou]`) 279 fmt.Println(re.ReplaceAllStringFunc("seafood fool", strings.ToUpper)) 280 // Output: 281 // SeaFooD FooL 282 } 283 284 func ExampleRegexp_SubexpNames() { 285 re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`) 286 fmt.Println(re.MatchString("Alan Turing")) 287 fmt.Printf("%q\n", re.SubexpNames()) 288 reversed := fmt.Sprintf("${%s} ${%s}", re.SubexpNames()[2], re.SubexpNames()[1]) 289 fmt.Println(reversed) 290 fmt.Println(re.ReplaceAllString("Alan Turing", reversed)) 291 // Output: 292 // true 293 // ["" "first" "last"] 294 // ${last} ${first} 295 // Turing Alan 296 } 297 298 func ExampleRegexp_SubexpIndex() { 299 re := regexp.MustCompile(`(?P<first>[a-zA-Z]+) (?P<last>[a-zA-Z]+)`) 300 fmt.Println(re.MatchString("Alan Turing")) 301 matches := re.FindStringSubmatch("Alan Turing") 302 lastIndex := re.SubexpIndex("last") 303 fmt.Printf("last => %d\n", lastIndex) 304 fmt.Println(matches[lastIndex]) 305 // Output: 306 // true 307 // last => 2 308 // Turing 309 } 310 311 func ExampleRegexp_Split() { 312 a := regexp.MustCompile(`a`) 313 fmt.Println(a.Split("banana", -1)) 314 fmt.Println(a.Split("banana", 0)) 315 fmt.Println(a.Split("banana", 1)) 316 fmt.Println(a.Split("banana", 2)) 317 zp := regexp.MustCompile(`z+`) 318 fmt.Println(zp.Split("pizza", -1)) 319 fmt.Println(zp.Split("pizza", 0)) 320 fmt.Println(zp.Split("pizza", 1)) 321 fmt.Println(zp.Split("pizza", 2)) 322 // Output: 323 // [b n n ] 324 // [] 325 // [banana] 326 // [b nana] 327 // [pi a] 328 // [] 329 // [pizza] 330 // [pi a] 331 } 332 333 func ExampleRegexp_Expand() { 334 content := []byte(` 335 # comment line 336 option1: value1 337 option2: value2 338 339 # another comment line 340 option3: value3 341 `) 342 343 // 正規表現パターンは、コンテンツから「key: value」のペアをキャプチャします。 344 pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`) 345 346 // 正規表現パターンでキャプチャされた値を参照して、 347 // "key: value"を "key=value"に変換するためのテンプレート。 348 template := []byte("$key=$value\n") 349 350 result := []byte{} 351 352 // 内容における正規表現の各マッチについて。 353 for _, submatches := range pattern.FindAllSubmatchIndex(content, -1) { 354 355 // キャプチャされたサブマッチをテンプレートに適用し、出力を結果に追加します。 356 result = pattern.Expand(result, template, content, submatches) 357 } 358 fmt.Println(string(result)) 359 // Output: 360 // option1=value1 361 // option2=value2 362 // option3=value3 363 } 364 365 func ExampleRegexp_ExpandString() { 366 content := ` 367 # comment line 368 option1: value1 369 option2: value2 370 371 # another comment line 372 option3: value3 373 ` 374 375 // 正規表現パターンは、コンテンツから "key: value" のペアをキャプチャします。 376 pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`) 377 378 // 正規表現パターンによってキャプチャされた値を参照して、 379 // "key: value"を "key=value" に変換するためのテンプレート。 380 template := "$key=$value\n" 381 382 result := []byte{} 383 384 for _, submatches := range pattern.FindAllStringSubmatchIndex(content, -1) { 385 // キャプチャされたサブマッチをテンプレートに適用し、出力を結果に追加します。 386 result = pattern.ExpandString(result, template, content, submatches) 387 } 388 fmt.Println(string(result)) 389 // Output: 390 // option1=value1 391 // option2=value2 392 // option3=value3 393 } 394 395 func ExampleRegexp_FindIndex() { 396 content := []byte(` 397 # comment line 398 option1: value1 399 option2: value2 400 `) 401 // 正規表現パターンは、コンテンツから「キー: 値」のペアをキャプチャします。 402 pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`) 403 404 loc := pattern.FindIndex(content) 405 fmt.Println(loc) 406 fmt.Println(string(content[loc[0]:loc[1]])) 407 // Output: 408 // [18 33] 409 // option1: value1 410 } 411 412 func ExampleRegexp_FindAllSubmatchIndex() { 413 content := []byte(` 414 # comment line 415 option1: value1 416 option2: value2 417 `) 418 // 正規表現パターンはコンテンツから "key: value" のペアをキャプチャします。 419 pattern := regexp.MustCompile(`(?m)(?P<key>\w+):\s+(?P<value>\w+)$`) 420 allIndexes := pattern.FindAllSubmatchIndex(content, -1) 421 for _, loc := range allIndexes { 422 fmt.Println(loc) 423 fmt.Println(string(content[loc[0]:loc[1]])) 424 fmt.Println(string(content[loc[2]:loc[3]])) 425 fmt.Println(string(content[loc[4]:loc[5]])) 426 } 427 // Output: 428 // [18 33 18 25 27 33] 429 // option1: value1 430 // option1 431 // value1 432 // [35 50 35 42 44 50] 433 // option2: value2 434 // option2 435 // value2 436 } 437 438 func ExampleRegexp_FindAllIndex() { 439 content := []byte("London") 440 re := regexp.MustCompile(`o.`) 441 fmt.Println(re.FindAllIndex(content, 1)) 442 fmt.Println(re.FindAllIndex(content, -1)) 443 // Output: 444 // [[1 3]] 445 // [[1 3] [4 6]] 446 }