Trying to split numbers with regex but returns only a few matches

So I’m doing Advent of Code with Odin, and I came with this issue. I want to split this numbers: 3,4,3,1,2 into a slice of ints, and for that I thought of using regex. This is the proc that I made to do this task:

split :: proc(inp: string) -> []int {
	re, err := regex.create(`([^,]+)`)

	if err != nil {
		fmt.printf("couldn't make regular expression: %s\n", err)
		os.exit(1)
	}

	defer regex.destroy_regex(re)

	cap, suc := regex.match_and_allocate_capture(re, inp)

	if !suc {
		fmt.println("no matches")
	} else {
		fmt.println(cap.groups)
	}

	nums := make([]int, len(cap.groups))

	for i in 0 ..< len(cap.groups) {
		num, ok := strconv.parse_int(cap.groups[i])

		if !ok {
			fmt.println("failed to convert string to int")
			os.exit(1)
		}
		nums[i] = num
	}

	return nums
}

however instead of having all the numbers into a slice I got this:

[3, 3]

idk if my regular expression is wrong and uses a different way to do regex but I tried many regexes and none of them gives me all the numbers I want to split. How I can achieve this?

I’m not familiar enough with regular expression syntax to assist fully, but there is already a split procedure in core:strings. You could do something like the following:

import "core:strings"
import "core:strconv"

parse_as_int_array :: proc(input: string) -> []int {
	values, split_error := strings.split(input, ", ")
	if split_error != nil { return nil }

	nums := make([]int, len(values))
	success: bool

	for value, index in values {
		nums[index], success = strconv.parse_int(value)
		if !success {
			delete(nums)
			return nil
		}
	}

	return nums
}

You don’t need a regex here. But I’ll give you two options besides what was given by Neighborly.

  1. Regex
import "core:text/regex"
import "core:strconv"

str := "1, 2, 3, 4"

iterator, err := regex.create_iterator(str, "\\d+")
if err != nil {
	fmt.println("Failed to create iterator:", err)
	return
}
defer regex.destroy_iterator(iterator)

numbers := make([dynamic]int)

for {
	capture, _ := regex.match_iterator(&iterator) or_break
	dig := strconv.parse_int(capture.groups[0]) or_break
	append(&numbers, dig)
}

fmt.println(numbers)
  1. Match
import "core:text/match"
import "core:strconv"

str := "1, 2, 3, 4"

m := match.matcher_init(str, "%d+")
dyn: [dynamic]int

for {
	word, _ := match.matcher_match_iter(&m) or_break
	dig := strconv.parse_int(word) or_break
	append(&dyn, dig)
}

fmt.println(dyn)

Both these will print the correct array - [1, 2, 3, 4]

You should use text/match when you can as it is simpler than regex. It’s modeled after lua matches.
And as Neigborly shown it’s much simpler to just use the strings package here as you don’t need a regex or match to do this task.

1 Like

Ok, thanks for the help!