Find regular expression text to match external specific characters

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:

  • Richard
  • Robert
  • Jill
+3
source share
6 answers

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 .

+2

:

step1: , :

\[[^\]]*\]

''

step2: (), :

\([^)]*\)
+3

IF, .NET, - :

"(?<!\[.*?)(?<name>\(\w+\))(?>!.*\])"
+1

- , , ? . , ( , ), , ; , , .

, /(?:(?:^|\])[^\[]*)\((.*?)\)/ ( - , [ ] , , ).

(PHP) :

preg_match_all('/(?:(?:^|\])[^\[]*)\((.*?)\)/', "My name is ... (Jill)", $m);

print(implode(", ", $m[1]));

:

Richard, Robert, Jill
0
>>> 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
0

, , , ? :

[^()]+(?=\)[^\[\]]*(?:\[[^\[\]]*\][^\[\]]*)*$)

, , , , .

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.

0
source

Source: https://habr.com/ru/post/1737557/


All Articles