# coding=utf8
# the above tag defines encoding for this document and is for Python 2.x compatibility
import re
regex = r"(?:\b\w++::\w++\s*+\(|\G(?<!^))\s*+(\w++)\s*+(?:\[[^]]*+]\s*+)?,"
test_str = ("Not even sure how to attack this Regex Need (Multiline text with extraction of library names)\n\n"
"Sample Text\n\n"
" box::use(\n"
" DBI[dbListTables, dbExecute],\n"
" Yessir[this_one, that one,\n"
" and_this_one],\n"
" Maybesir[\n"
" func_one,\n"
" func_two,\n"
" ],\n"
" Nosir,\n"
" \n"
" database = logic/database,\n"
" log = logic/log,\n"
" options = logic/options,\n"
" utilities = logic/utilities,\n"
" )\n\n"
"I would like to have a regexp which matches the following from the above text:\n\n"
" DBI, Yessir, Maybesir, Nosir\n\n"
"Is there an easy way to approach this? I have been trying to use the regexp101 website to help me out here, but this one is sufficiently complex that I am a bit out of my depth. My current line is the following:\n\n"
" box::use\\(\\n(?:[\\s]*([A-Za-z0-9]*)(?:[A-Za-z0-9\\[\\]_\\ ,]*\\n))\n\n"
"But, this is of course not getting it. I am not sure how to handle getting the multiple (unknown how many there really would be) libraries inside the box::use function.\n\n"
"It might be easier to extract the text from inside the use::box function first and then regexp that?\n\n"
" \n"
"Edit: Forgot to add that I am using Python3")
matches = re.finditer(regex, test_str, re.MULTILINE)
for matchNum, match in enumerate(matches, start=1):
print ("Match {matchNum} was found at {start}-{end}: {match}".format(matchNum = matchNum, start = match.start(), end = match.end(), match = match.group()))
for groupNum in range(0, len(match.groups())):
groupNum = groupNum + 1
print ("Group {groupNum} found at {start}-{end}: {group}".format(groupNum = groupNum, start = match.start(groupNum), end = match.end(groupNum), group = match.group(groupNum)))
# 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