Regular expression to match underscores not surrounded by parentheses?

Can anyone suggest a regex to match the underscore in the following examples:

test_test
test[_test
test_]

But does NOT match this:

test[_]test

This is using the .Net Regular Expression library. I use this RegEx tester to check:

http://derekslager.com/blog/posts/2007/09/a-better-dotnet-regular-expression-tester.ashx

+3
source share
5 answers

Try the following:

_[^\]]|[^[]_

It consists of alternation _[^\]](underscore, not ]) and [^[]_(not [and underscore).

Or if you want to use look-around statements to really only match underscores, not surrounding characters:

_(?=[^\]])|_(?<=[^[]_)

, ] ((?=[^\]]), ) , [ ((?<=[^[]_), ). :

_(?:(?=[^\]])|(?<=[^[]_))
+5
_(?!\](?<=\[_\]))

, . , , . "_]" , , :

_(?!\](?<=\[..))

lookbehind , :

_(?<!\[_(?=\]))

, lookaround , NOT (x AND y).

EditPad Pro, , :

test_test
test[_test
test_]
_]Test
Test[_
test[_]test

EDIT: :

(?<!\[)_|_(?!\])

, , , . , , "(NOT x) OR (NOT y)" lookbehind .

+2

.Net, , , , , :

[^\[](_)|(_)[^\]]

: , , :

[^\[](_)|(_)[^\]]|^_|_$
+1

((|?! (]))

which uses a negative lookahead / behind (rather than a positive lookahead / behind and excluded characters).

+1
source

Try

^.*(\[_[^\]])|([^\[]_\])|([^\[]_[^\]]).*$

EDIT: Now processing

test_test

Not verified, but read: Any character string followed by either [_ , then any character, but ] or any character, but [then_]

Note. This can lead to failure in cases such as

_]Test
Test[_

I do not know if this problem was for you?

Tested successfully with all your examples

0
source

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


All Articles