I am trying to find a substring between two words, but my starting word contains an apostrophe and I can't seem to match it.
For example, in this following sentence
bus driver drove steady although the bus's steering was going nuts.
the correct answer to my search should be:
steering was going nuts
and not:
driver ... nuts
I tried this
re := regexp.MustCompile("(?s)bus[\\\'].*?nuts")
I also tried this:
re := regexp.MustCompile("(?s)bus'.*?nuts")
Can't seem to make it work.
You could use a string literal (with back quote) in order to include a single quote, with a capturing group:
re := regexp.MustCompile(`(?s)bus'.\s+(.*?nuts)`)
See this example:
var source_txt = `bus driver drove steady although the bus's steering was going nuts.`
func main() {
fmt.Printf("Experiment with regular expressions.
")
fmt.Printf("source text:
")
fmt.Println("--------------------------------")
fmt.Printf("%s
", source_txt)
fmt.Println("--------------------------------")
// a regular expression
regex := regexp.MustCompile(`(?s)bus'.\s+(.*?nuts)`)
fmt.Printf("regex: '%v'
", regex)
matches := regex.FindStringSubmatch(source_txt)
for i, v := range matches {
fmt.Printf("match %2d: '%s'
", i+1, v)
}
}
Output:
Experiment with regular expressions.
source text:
--------------------------------
bus driver drove steady although the bus's steering was going nuts.
--------------------------------
regex: '(?s)bus'.\s+(.*?nuts)'
match 1: 'bus's steering was going nuts'
match 2: 'steering was going nuts'
The FindStringSubmatch()
:
identifying the leftmost match of the regular expression in s and the matches, if any, of its subexpressions
The match[1]
would be the first capturing group.
The correct answer to my search should be
"steering was going nuts"
...
If you want that substring as your match result, you should adjust your regex accordingly.
re := regexp.MustCompile("(?s)bus's (.*?nuts)")
rm := re.FindStringSubmatch(str)
if len(rm) != 0 {
fmt.Printf("%q
", rm[0]) // "bus's steering was going nuts"
fmt.Printf("%q", rm[1]) // "steering was going nuts"
}