v2 / examples / regex / pcre.v
69 lines · 53 sloc · 1.47 KB · 5b2db043fa1e6c3709fa0eb27f85be4f96db6f02
Raw
1import regex.pcre
2
3// Since 2026/02/08, regex.pcre is built-in and implemented in pure V.
4// The same example will compile and run with the C wrapper of the PCRE library
5// too, but you will need to `import pcre` instead.
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}
70