Python (re)

GraphQL Operation Header in PY

Match GraphQL operation headers — `query`, `mutation`, or `subscription` — capturing the operation name.

Try it in the PY tester →

Pattern

regexPY
(query|mutation|subscription)\s+(\w+)?\s*(?:\([^)]*\))?\s*\{   (flags: g)

Python (re) code

pyPython
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+.

How the pattern works

(query|mutation|subscription) captures the operation type. \s+(\w+)? optionally captures the operation name (anonymous operations omit it). (?:\([^)]*\))? optionally matches a variables declaration `($var: Type)`. The trailing `\s*\{` matches the opening brace of the selection set.

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 graphql

No match

Same pattern, other engines

← Back to GraphQL Operation Header overview (all engines)