# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"^(?<indent>\s*)(?<mod1>\w+)\s(?<mod2>\w+)?\s*(?<mod3>\w+)?\s*(?<return>\b\w+)\s(?<name>\w+)\((?<arg>.*?)\)\s*\{(?<body>.+?)^\k<indent>\}"
test_str = ("public static FieldsConfig getFieldsConfig(){\n"
" if(xxx) {\n"
" sssss;\n"
" }\n"
" return;\n"
"}\n\n"
" public String getAsSeparateGroup(String groupName) {\n"
" String begin = pattern.substring(0,getStart());\n"
" String mid = pattern.substring(getStart(),getEnd());\n"
" String finish = pattern.substring(getEnd());\n"
" return begin + \"(?<\" + groupName + \">\" + mid + \")\" + finish;\n"
" }\n\n"
" @Override\n"
" public static final String toString() {\n"
" return asString;\n"
" }\n\n"
" public String directMatch(String match) {\n"
" Matcher matcher = Pattern.compile(getAsSeparateGroup(\"test\")).matcher(match);\n"
" matcher.find();\n"
" String result;\n"
" try {\n"
" result = matcher.group(\"test\");\n"
" }catch (Exception ex) {\n"
" result = \"empty\";\n"
" }\n"
" return getPattern() + \":\" + result;\n"
" }\n"
"}")
subst = ""
# You can manually specify the number of replacements by changing the 4th argument
result = re.sub(regex, subst, test_str, 0, re.MULTILINE | re.DOTALL)
if result:
print (result)
# Note: for Python 2.7 compatibility, use ur"" to prefix the regex and u"" to prefix the test string and substitution.
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