import re
regex = re.compile(r"^.*getInitialProps[\s\S]*?\bdispatch[\s\S]*?(return).*\n.*", flags=re.MULTILINE)
test_str = ("import React from 'react'\n\n"
"class Page extends React.Component {\n"
" static async getInitialProps(ctx) {\n"
" const res = await fetch('https://api.github.com/repos/zeit/next.js')\n"
" const json = await res.json()\n"
" dispatchEvent(event)\n"
" return { stars: json.stargazers_count }\n"
" }\n\n"
" render() {\n"
" return <div>Next stars: {this.props.stars}</div>\n"
" }\n"
"}\n\n"
"export default Page\n\n"
"class Page extends React.Component {\n"
" static async getInitialProps(ctx) {\n"
" const res = await fetch('https://api.github.com/repos/zeit/next.js')\n"
" const json = await res.json()\n"
" return { stars: json.stargazers_count }\n"
" }\n\n"
" render() {\n"
" return <div>Next stars: {this.props.stars}</div>\n"
" }\n"
"}")
matches = regex.finditer(test_str)
for match_num, match in enumerate(matches, start=1):
print(f"Match {match_num} was found at {match.start()}-{match.end()}: {match.group()}")
for group_num, group in enumerate(match.groups(), start=1):
print(f"Group {group_num} found at {match.start(group_num)}-{match.end(group_num)}: {group}")
Please keep in mind that these code samples are automatically generated and are not guaranteed to work. If you find any syntax errors, feel free to submit a bug report. For a full regex reference for Python, please visit: https://docs.python.org/3/library/re.html