简体   繁体   中英

Regex any alphanumeric sequence except a specific string

I am trying to match anything containing foo<sequence of alphanumeric or space>baz except foo<sequence of alphanumeric or space>barbaz

So this would match:

foohello there baz
foobarmystringbaz

And this must not match

foohellobarbaz

I currently have .*\\b(foo[a-zA-Z0-9 ]+baz)\\b.* which is working fine. But I am stumped trying to add the restriction.

EDIT : I am trying to get a capture group to get the matching part, so

foohellobaz barbaz

should match, but only capture foohellobaz

If I understand correctly, you mean the string may never end with barbaz. This is done using the following regex:

\bfoo[a-zA-Z0-9 ]+(?<!bar)baz\b

https://regex101.com/r/8EggsE/2

EDIT:

I updated the regex to match 'foohellobaz' in 'foohellobaz barbaz'.

Just to add another one (with a neg. lookahead):

^(?!.*barbaz$)foo[\w ]+baz$

See a demo on regex101.com .


As @Harm van der Warl points out, \\w does include an underscore as well and is the same as [a-zA-Z0-9_] . This may or may not what you want.

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