I have a text that looks like this:
My name is (Richard) and I can’t [anything (Jack) can’t do] and (Robert) in the same way [unlike (Betty)] thanks (Jill)
The goal is to search using a regular expression to find all the names in brackets that appear anywhere in the text, but between any brackets.
So, in the text above, the result I'm looking for is:
You did not say what language you use, so here are a few Python:
>>> import re >>> REGEX = re.compile(r'(?:[^[(]+|\(([^)]*)\)|\[[^]]*])') >>> s="""My name is (Richard) and I cannot do [whatever (Jack) can't do] and (Robert) is the same way [unlike (Betty)] thanks (Jill)""" >>> filter(None, REGEX.findall(s))
Conclusion:
['Richard', 'Robert', 'Jill']
, . , , - , . . ( .)
, , parens, , . ( ) . Python findall . . , findall , filter .
findall
filter
:
step1: , :
\[[^\]]*\]
''
step2: (), :
\([^)]*\)
IF, .NET, - :
"(?<!\[.*?)(?<name>\(\w+\))(?>!.*\])"
- , , ? . , ( , ), , ; , , .
, /(?:(?:^|\])[^\[]*)\((.*?)\)/ ( - , [ ] , , ).
/(?:(?:^|\])[^\[]*)\((.*?)\)/
[
]
(PHP) :
preg_match_all('/(?:(?:^|\])[^\[]*)\((.*?)\)/', "My name is ... (Jill)", $m); print(implode(", ", $m[1]));
Richard, Robert, Jill
>>> s="My name is (Richard) and I cannot do [whatever (Jack) can't do (Jill) can] and (Robert) is the same way [unlike (Betty)] thanks (Jill)" >>> for item in s.split("]"): ... st = item.split("[")[0] ... if ")" in st: ... for i in st.split(")"): ... if "(" in i: ... print i.split("(")[-1] ... Richard Robert Jill
, , , ? :
[^()]+(?=\)[^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*$)
, , , , .
I say this should work, because although I tested it, I don’t know which language / tool you use to match the regular expression. We could provide better answers if we had this information; all regular expressions are not created equal.
Source: https://habr.com/ru/post/1737557/More articles:DWM and drawing non-responsive applications - windows-vistaQt: reloading resources on each compilation - qtHow can I detect message boxes appearing in another process? - c ++How to run a task before updating the source files? - cruisecontrol.netAjax в плагине Firefox - firefox-addonASP / VBScript ServerXmlHttp Encoding - encodingz-index does not affect IE7 using Google Map and navigation submenus - cssКакие атаки XSS/CSRF (если они есть) должны быть осведомлены о том, когда разрешено использование видео? - phpCreating a compile-time array for ANSI-C? - cphp: avoid __get in certain circumstances? - phpAll Articles