简体   繁体   中英

Regex at the beginning of a string in context

I've got the following RegEx-Pattern:

pattern = @"(?<=\[)[\da-f]{8}(?=\])";

It extracts " f000000f " out of " [f000000f] Bar " correctly, but it should not match on " Foo [f000000f] Bar " so i've added the ^ to determine the beginning of the pattern:

pattern = @"^(?<=\[)[\da-f]{8}(?=\])";

But this pattern doesn't work for both inputs.

Can anybody tell me how to force the first pattern to match only at the beginning of the input-String?

Thanks in advance.

You need to move the anchor inside the lookbehind, like this:

(?<=^[)[\da-f]{8}(?=])"

Otherwise, you wouldn't match [f000000f] , because no part of your expression "consumes" the opening square bracket [ .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM