Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Matching any character except an underscore using Regex

I'm trying to write Regex that will match a string of characters EXCEPT strings with an underscore.

I have this so far /[A-Za-z0-9]+/ but I don't know what to include in it to make it require no underscore.

UPDATE:

Is should have made this more clear off the bat. I am trying to match an email address, but not email addresses that have an underscore in the portion after the _

This is what I have in total so far. /[A-Za-z_0-9]+@[A-Za-z0-9]+\.(com|ca|org|net)/ The answers as of yet, don't work

like image 217
CodyBugstein Avatar asked Mar 04 '13 16:03

CodyBugstein


People also ask

How do I match a character except space in regex?

[^ ] matches anything but a space character.

Is underscore a special character in regex?

[0-9] —The string can contain any number between 0–9. [_-] —The string can contain an underscore or hyphen. Both the underscore and the hyphen are called special characters. Special characters include any non-alphanumeric characters, such as punctuation or symbols.

How do you match a character except one?

To match any character except a list of excluded characters, put the excluded charaters between [^ and ] . The caret ^ must immediately follow the [ or else it stands for just itself.

What regex matches any character?

By default, the '. ' dot character in a regular expression matches a single character without regard to what character it is. The matched character can be an alphabet, a number or, any special character.


2 Answers

/^[^_]+$/ would match a string of 1 or more character containing any character except underscore.

like image 98
rvalvik Avatar answered Oct 04 '22 00:10

rvalvik


If I understand what you're asking for - matching strings of characters, except for strings of characters that contain an underscore - this requires regex lookahead.

The reason is that regular expressions normally operate one character at a time. So if I want to know if I should match a character, but only if there is not an underscore later, I need to use lookahead.

^((?!_)[A-Za-z0-9])+$

?! is the negative lookahead operator

EDIT:

So you want there to be at most one underscore in the portion before the @ sign, and no underscore in the portion after?

^[A-Za-z0-9]+_?[A-Za-z0-9]+@[A-Za-z0-9]+\.(com|ca|org|net)$

like image 28
Ryan O. Avatar answered Oct 04 '22 01:10

Ryan O.