Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regexp - only if first character is not an asterisk

I am using a javascript validator which will let me build custom validation based on regexp

From their website: regexp=^[A-Za-z]{1,20}$ allow up to 20 alphabetic characters.

This will return an error if the entered data in the input field is outside this scope.

What I need is the string that will trigger an error for the inputfield if the value has an asterix as the first character.

I can make it trigger the opposite (an error if the first character is NOT an asterix) with:

regexp=[\u002A]

Heeeeelp please :-D

like image 452
Splynx Avatar asked Mar 14 '11 01:03

Splynx


People also ask

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string). Both are called anchors and ensure that the entire string is matched instead of just a substring.

What is the difference between * and in regex?

represents any single character (usually excluding the newline character), while * is a quantifier meaning zero or more of the preceding regex atom (character or group). ? is a quantifier meaning zero or one instances of the preceding atom, or (in regex variants that support it) a modifier that sets the quantifier ...

How do you match an asterisk in regex?

To match a special character, precede it with a backslash, like this \* . A period (.) matches any character except a newline character. You can repeat expressions with an asterisk or plus sign.

What is U flag in regex?

Flag u enables the support of Unicode in regular expressions. That means two things: Characters of 4 bytes are handled correctly: as a single character, not two 2-byte characters. Unicode properties can be used in the search: \p{…} .


1 Answers

How about:

^[^\*]

Which matches any input that does not start with an asterisk; judging from the example regex, any input which does not match the regex will be cause a validation error, so with the double negative you should get the behaviour you want :-)

Explanation of my regex:

  • The first ^ means "at the start of the string"
  • The [ ... ] construct is a character class, which matches a single character among the ones enclosed within the brackets
  • The ^ in the beginning of the character class means "negate the character class", i.e. match any character that's not one of the ones listed
  • The \* means a literal *; * has a special meaning in regular expressions, so I've escaped it with a backslash. As Rob has pointed out in the comments, it's not strictly necessary to escape (most) special characters within a character class
like image 83
Cameron Avatar answered Oct 27 '22 19:10

Cameron