简体   繁体   中英

Regex - Does not contain certain characters except for end

I need to match any lines that end with "&" but does not contain "," or "&" in between.

a b c &

a, b, c, &

a & b, c &

a & b

I was able to get partial success by using:

^(?!.*,).*&.*$

and I got both:

a b c &
a & b

So I've tried it with

^(?!.*(,|&)).*&.*$

And I'm unable to get any matches. How can I modify my regex so I can only get abc & ? I am using .NET

Seems you should get what you need by using a negated character class, eg

^[^,&]*&\s*$

using the multiline flag.

You can replace \\s* by \\r? if you don't want to allow trailing spaces as suggested by revo.

You might also want to add the newline character to the negated character class ( [^,&\\n] ) if you are working with multiline text (instead of testing line for line) to avoid overlapping matches.

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