GraphQL Operation Header
Match GraphQL operation headers — `query`, `mutation`, or `subscription` — capturing the operation name.
Try it in RegexPro →Available in
JavaScript / ECMAScript code
const re = new RegExp("(query|mutation|subscription)\\s+(\\w+)?\\s*(?:\\([^)]*\\))?\\s*\\{", "g");
const input = "query GetUser($id: ID!) { user(id: $id) { name } }";
const matches = [...input.matchAll(re)];
console.log(matches.map(m => m[0]));Uses `String.prototype.matchAll` for global iteration (Node 12+ / all modern browsers).
Python (re) code
import re
pattern = re.compile(r"(query|mutation|subscription)\s+(\w+)?\s*(?:\([^)]*\))?\s*\{")
input_text = "query GetUser($id: ID!) { user(id: $id) { name } }"
for m in pattern.finditer(input_text):
print(m.group(0))Stdlib `re` module — no third-party dependency. Works on Python 3.6+.
Go (RE2) code
package main
import (
"fmt"
"regexp"
)
func main() {
re := regexp.MustCompile(`(query|mutation|subscription)\s+(\w+)?\s*(?:\([^)]*\))?\s*\{`)
input := `query GetUser($id: ID!) { user(id: $id) { name } }`
for _, match := range re.FindAllString(input, -1) {
fmt.Println(match)
}
}Uses `regexp.MustCompile` (panics on bad patterns at startup) and `FindAllString` for all matches.
Pattern
(query|mutation|subscription)\s+(\w+)?\s*(?:\([^)]*\))?\s*\{ (flags: g)Raw source: (query|mutation|subscription)\s+(\w+)?\s*(?:\([^)]*\))?\s*\{
How it works
Examples
Input
query GetUser($id: ID!) { user(id: $id) { name } }Matches
query GetUser($id: ID!) {
Input
mutation { createPost(title: "hi") { id } }Matches
mutation {
Input
// not graphqlNo match
—Common use cases
- •GraphQL operation registry / persisted-queries
- •Linting (require named operations, etc.)
- •Apollo / urql client introspection
- •Static analysis for n+1 query risks
Related patterns
Terraform Resource Block Header
Text ProcessingMatch the opening line of a Terraform `resource "type" "name" {` block, capturing the resource type and local name.
Keep-a-Changelog Entry Header
Text ProcessingMatch Keep-a-Changelog style version headers like `## [1.2.3] - 2024-01-15` or `## 2.0.0`.
JavaScript Variable Declaration
Text ProcessingMatch JavaScript / TypeScript variable declarations (`var`, `let`, `const`), capturing the keyword and identifier name.
HCL / Terraform Variable Reference
Text ProcessingMatch Terraform / HCL references like `var.name`, `local.foo`, `module.x.output`, or `data.aws_ami.ubuntu.id`.