How to parse CSV files using regular expressions in Go? 1. Import the regexp library. 2. Use regexp.MustCompile to create a regular expression that matches the CSV row fields. 3. Use the regexp.Split function to split the CSV row into an array of strings. 4. A practical case shows how to use regular expressions to parse CSV files containing personnel data.
How to use regular expressions to parse CSV files in Go
Regular expressions (regex) are a powerful tool. For matching and processing text. In Go, we can use the regexp
package to process CSV files.
1. Import library
import ( "fmt" "regexp" )
2. Match CSV rows
Useregexp.MustCompile
Create a regular expression pattern that matches fields in a CSV row:
re := regexp.MustCompile(`^([^,]*),([^,]*),(.+)$`)
This pattern matches each field with three capturing groups.
3. Parse CSV rows
Use the regexp.Split
function to split the CSV row into an array of strings:
line := "John,Doe,jdoe@example.com" fields := re.Split(line, -1)
fields
The array now contains three elements: name, last name, and email address.
4. Practical case
Let us use regular expressions to parse a CSV file containing personnel data:
package main import ( "fmt" "io/ioutil" "regexp" ) func main() { // 读取 CSV 文件 data, err := ioutil.ReadFile("people.csv") if err != nil { fmt.Println(err) return } // 使用正则表达式解析 CSV 行 re := regexp.MustCompile(`^([^,]*),([^,]*),(.+)$`) lines := strings.Split(string(data), "\n") for _, line := range lines { fields := re.Split(line, -1) if len(fields) != 4 { fmt.Println("无效的行:", line) continue } // 打印个人信息 fmt.Printf("%s %s (%s)\n", fields[1], fields[2], fields[3]) } }
The above is the detailed content of How to parse CSV files using regular expressions in Go?. For more information, please follow other related articles on the PHP Chinese website!