KJ Saxena
KJ Saxena

Reputation: 21828

What regex will match every character except comma ',' or semi-colon ';'?

Is it possible to define a regex which will match every character except a certain defined character or set of characters?

Basically, I wanted to split a string by either comma (,) or semi-colon (;). So I was thinking of doing it with a regex which would match everything until it encountered a comma or a semi-colon.

Upvotes: 455

Views: 511085

Answers (4)

knittl
knittl

Reputation: 265141

Use a negative character class:

[^,;]+

This will match at least one character that is not a comma nor a semicolon. If there are multiple characters matching this criterion, all of them will be matched (+ at-least-once quantifier)

Upvotes: 56

NawaMan
NawaMan

Reputation: 932

Use this:

([^,;]*[,;])*

Upvotes: 3

Thom Smith
Thom Smith

Reputation: 14086

Use character classes. A character class beginning with caret will match anything not in the class.

[^,;]

Upvotes: 109

Mehrdad Afshari
Mehrdad Afshari

Reputation: 421968

[^,;]+         

You haven't specified the regex implementation you are using. Most of them have a Split method that takes delimiters and split by them. You might want to use that one with a "normal" (without ^) character class:

[,;]+

Upvotes: 599

Related Questions