C # regex for a word possibly surrounded by quotation marks

For the C # program I am writing, I use regular expressions to search for a specific pattern, and this pattern may or may not be surrounded by brackets, but if so, I want to include them in the match.

So, for example, let's say that my template was just a word "hello", I created this regular expression:

"\(?hello\)?"

But this does not take into account that the word must have BOTH opening and closing parentheses in order to qualify as a match. So, for example, if my search string was:

hello, (hello), (hello, my name is bob), (bob said hello)

I would like to have the next 4 matches - hello, (hello) hello,hello

In particular, the second match includes parentheses, but the 3rd and 4th matches do not contain any parentheses , since they are not at the beginning and end with “hello”.

What regular expression can be used to accomplish this?

+4
source share
2 answers

You can simply use alternation to match \(hello\)or hello:

\(hello\)|hello

Because regular expressions are inherently greedy, (hello)will match up hello, which means that all four instances will be matched.

+3
source

- , ( , , !!!)

:

(\()?hello(?(1)\))

, - , , , , , , - !

+2

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


All Articles