Golang正则表达式排除匹配:提取Google Data Studio仪表盘所需字符串片段
Extract Text Between Hyphen and First Colon in Go
Got it, let's fix this regex issue for you! The problem with your original pattern ([\-].*[\:]) is twofold: it includes the hyphen and colon in the match, and the greedy .* will match all the way to the last colon instead of the first one. Here's how to get just the text in between:
Solution 1: Use a Capturing Group (Most Reliable for Go)
Go's regexp package works great with capturing groups to isolate the exact content you want. Use this pattern:
-\s*(.*?):
Let's break it down:
-\s*: Matches the hyphen followed by any number of whitespace characters (so it handles spaces after the hyphen cleanly)(.*?): A non-greedy capture group that grabs everything until the first colon it encounters:: Stops the match at the first colon
Here's a complete Go code example to implement this:
package main import ( "fmt" "regexp" "strings" ) func main() { targetStr := "ABC - What I need::Other Information I do not need" // Compile the regex pattern re := regexp.MustCompile(`-\s*(.*?):`) // Find the first match and its capture groups matchResults := re.FindStringSubmatch(targetStr) // Check if we found a valid match (the first element is the full match, the second is our captured content) if len(matchResults) > 1 { extractedText := matchResults[1] fmt.Println("Extracted content:", extractedText) // Output: What I need // If you want to trim any extra whitespace around the text: trimmedText := strings.TrimSpace(extractedText) fmt.Println("Trimmed content:", trimmedText) } else { fmt.Println("No match found") } }
Why Your Original Pattern Failed
[\-].*[\:]: The.*is greedy, so it matches as much as possible—meaning it will go all the way to the last colon in your string, not the first.- You included the hyphen and colon inside the capture group, so they get included in the matched text. Using a separate capture group for the middle content avoids this.
Bonus: Handling Edge Cases
- If there's no space after the hyphen (e.g.,
ABC-What I need::...), the\s*will still work since it matches zero or more spaces. - If you want to exclude any leading/trailing whitespace in the extracted text, use
strings.TrimSpace()on the captured result as shown in the example.
内容的提问来源于stack exchange,提问作者pscl
相关产品推荐
相关产品推荐

