1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00

regex: add split (#14329)

This commit is contained in:
David 'Epper' Marshall
2022-05-08 08:21:39 -04:00
committed by GitHub
parent 084f2867b6
commit 650fb493bd
2 changed files with 274 additions and 165 deletions

View File

@@ -293,6 +293,38 @@ pub fn (mut re RE) find_all(in_txt string) []int {
return res
}
// split returns the sections of string around the regex
//
// Usage:
// ```v
// blurb := 'foobar boo steelbar toolbox foot tooooot'
// mut re := regex.regex_opt('f|t[eo]+')?
// res := re.split(blurb) // ['bar boo s', 'lbar ', 'lbox ', 't ', 't']
// ```
pub fn (mut re RE) split(in_txt string) []string {
pos := re.find_all(in_txt)
mut sections := []string{cap: pos.len / 2 + 1}
if pos.len == 0 {
return [in_txt]
}
for i := 0; i < pos.len; i += 2 {
if pos[i] == 0 {
continue
}
if i == 0 {
sections << in_txt[..pos[i]]
} else {
sections << in_txt[pos[i - 1]..pos[i]]
}
}
if pos[pos.len - 1] != in_txt.len {
sections << in_txt[pos[pos.len - 1]..]
}
return sections
}
// find_all_str find all the non overlapping occurrences of the match pattern, return a string list
[direct_array_access]
pub fn (mut re RE) find_all_str(in_txt string) []string {