v / examples / regex
Raw file | 69 loc (52 sloc) | 1.34 KB | Latest commit hash 3f3bec45f
1module main
2
3// NB: you need to `v install pcre` to be able to compile this example.
4
5import pcre
6
7fn example() {
8 r := pcre.new_regex('Match everything after this: (.+)', 0) or {
9 println('An error occurred!')
10 return
11 }
12
13 m := r.match_str('Match everything after this: "I ❤️ VLang!"', 0, 0) or {
14 println('No match!')
15 return
16 }
17
18 // m.get(0) -> Match everything after this: "I ❤️ VLang!"
19 // m.get(1) -> "I ❤️ VLang!"'
20 // m.get(2) -> Error!
21 whole_match := m.get(0) or {
22 println('We matched nothing...')
23 return
24 }
25
26 matched_str := m.get(1) or {
27 println('We matched nothing...')
28 return
29 }
30
31 println(whole_match) // Match everything after this: "I ❤️ VLang!"
32 println(matched_str) // "I ❤️ VLang!"
33}
34
35fn main() {
36 example()
37
38 mut text := '[ an s. s! ]( wi4ki:something )
39 [ an s. s! ]( wi4ki:something )
40 [ an s. s! ](wiki:something)
41 [ an s. s! ](something)dd
42 d [ an s. s! ](something ) d
43 [ more text ]( something ) s [ something b ](something)dd
44
45 '
46
47 // check the regex on https://regex101.com/r/HdYya8/1/
48
49 regex := r'(\[[a-z\.\! ]*\]\( *\w*\:*\w* *\))*'
50
51 r := pcre.new_regex(regex, 0) or {
52 println('An error occurred!')
53 return
54 }
55
56 m := r.match_str(text, 0, 0) or {
57 println('No match!')
58 return
59 }
60
61 whole_match1 := m.get(0) or {
62 println('We matched nothing 0...')
63 return
64 }
65
66 println(whole_match1)
67
68 println(m.get_all())
69}