简体   繁体   中英

Exactly one occurrence in regex

I have a regex:

@"\s*[\( \[ \{]\s*[a]\s*[n]\s*[\} \] \)]\s*"

than detects a string within exactly one opening and closing braces: ( [ { even if there is any number of spaces in the string anywhere.

But the problem is that it also detects 'an' if not within braces. How do I instruct regex to detect the string 'an' only within exactly one opening and closing braces.

abc an abc should not match.

I want to match string like:

abc [ an ] abc
abc { a n } abc
abc   (   a       n     ) abc

And can the brackets type be matched? I mean is it possible to match only those that have closing bracket same as opening bracket?

Try removing the spaces in the square brackets. It's most likely matching those.

@"\s*[\(\[\{]\s*[a]\s*[n]\s*[\}\]\)]\s*"

Also, FWIW, this pattern doesn't check to ensure brackets are the same. It will get, eg, [an} or (an] .

To do this, you'd need something like:

\(\s*a\s*n\s*\)|\{\s*a\s*n\s*\}|\[\s*a\s*n\s*\]

I'm sure there's a prettier way, but it's escaping me right now.

Try this:

^(\[ \( \{an\} \] \))$

This only allow the follow string:

[ ( {an} ] )

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