Write me a vimscript compatible regex that I can use in the search function to match Go…
- User
Write me a vimscript compatible regex that I can use in the search function to match Go test functions:
func TestXXX(t *testing.T)
but not
func TestXXX()
- Assistant
In Vimscript, you can write a regular expression to match Go test functions that include the
*testing.Tparameter. You can use this regex pattern to search for such functions specifically:/vim \(func\s\+Test\w\+\s*(t\s\*\s*testing\.T)\)Here's a breakdown of the regex pattern:
func\s\+: Matches the keywordfuncfollowed by one or more whitespace characters.Test\w\+: Matches the prefixTestfollowed by one or more word characters. This assumes that the function name starts withTest, as per Go convention.\s*: Matches any optional whitespace between the function name and the opening parenthesis.(: Matches the literal opening parenthesis.t\s\*: Matches the variabletfollowed by optional whitespace.testing\.T: Matches the type*testing.T.): Matches the literal closing parenthesis.
This regex should be entered within Vim's search function to locate function signatures that match Go's test function pattern when the parameter is present.
- User
No tests found when I run it with
let test_regex = "(func\s+Test\w+\s*(t\s*\s*testing.T))" let l:line = search(test_regex, "bcnW")
- Assistant
If you're using the
search()function in Vimscript, you need to adjust the regex to ensure it escapes properly within the context of Vim. Also, the search function does not need the outer parentheses if you're just looking to match; those are generally used for capturing groups. Here's how you can set it up:let test_regex = 'func\s\+Test\w\+\s*(t\s*\*\s*testing\.T)' let l:line = search(test_regex, 'bcnW')Here are some things to check:
-
Use of Single Quotes: In Vimscript, use single quotes for defining the regex string when backslashes are used, as this avoids the need to escape the backslashes themselves.
-