I don’t know much about regex, but I’m trying to use this regex made by chatGPT in vscode but it returns nothing as result. But when I try to use in another site like https://regex101.com/, the string matches.
Regex:
throws+news+ApiResponseErrors*(s*HttpStatusCode.([^,]+),s*('[^']*'|"[^"]*"),s*news+Error(`([^`]*)`),s*(true|false)?s*)
Pattern that matches in the site:
throw new ApiResponseError(
HttpStatusCode.BAD_REQUEST,
'low',
new Error(`Required parameters of the '${worksheetDefinitions.worksheetName}' worksheet were not informed`),
false
)
Note the blank spaces, i need them in the regex as well.
Is there any configuration I need to do?
I tried to change the regex, search for solutions but it keeps returning nothing. I expected that the regex works like in the site.
2
Answers
Add
[sn]*
to your regex like this:throws+news+ApiResponseError[sn]*(s*HttpStatusCode.([^,]+),s*('[^']*'|"[^"]*"),s*news+Error(
([^]*)
),s*(true|false)?s*)`which as @Wiktor mentioned is necessary because vscode handles newlines in a different way than regex engines. For performance reasons you need to explicitly tell vscode to look for newlines with a literal
n
not justs
(which would otherwise include newlines but doesn’t here in vscode).So using
[sn]*
tells vscode to look for newlines as well as the others
operstions.You can make any regex for Visual Studio Code match across line breaks if you specify
n{0}
anywhere inside the pattern, the most convenient places are start and end of the pattern. I’d recommend putting it at the start so as not to break any specific regex constructs if you are not familiar with regular expressions that much.So, the rule is
n{0}
+YOUR_REGEX
.VSCode regex engine requires
n
to be present in the pattern so that any construct likes
or[^"]
could match line break chars, and defining a "match zero newlines" pattern does the job.In your case, you can use
If you have other issues matching any character with a VSCode regex, see Multi-line regular expressions in Visual Studio Code.