Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regular expression start with specific letter

Tags:

regex

I am using this ^[S-s][0-9]{4}$ to validate my string, but not working properly. my string has to be in the form of the Letter S (upper-case or lower-case) followed by 4 digits, e.g. S1234. Looks like it works for Letters above S, meaning if I enter w1234 it validates correct, but if I enter a letter below s, like a1234 it doesn’t validate. Thanks.

like image 759
user282807 Avatar asked Dec 16 '11 21:12

user282807


People also ask

How do you match A specific letter in regex?

There is a method for matching specific characters using regular expressions, by defining them inside square brackets. For example, the pattern [abc] will only match a single a, b, or c letter and nothing else.

How do you search for A regex pattern at the beginning of A string?

The meta character “^” matches the beginning of a particular string i.e. it matches the first character of the string. For example, The expression “^\d” matches the string/line starting with a digit. The expression “^[a-z]” matches the string/line starting with a lower case alphabet.

What is the regex for special characters?

Special Regex Characters: These characters have special meaning in regex (to be discussed below): . , + , * , ? , ^ , $ , ( , ) , [ , ] , { , } , | , \ . Escape Sequences (\char): To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ).

How do I find the first character in A regular expression?

Using the regular expressions.The matches() method of the String class accepts a regular expression and verifies it matches with the current String, if so, it returns true else, it returns false. The regular expression to match String which contains a digit as first character is “^[0-9]. *$”.


2 Answers

You need to get rid of the dash:

^[Ss][0-9]{4}$

dashes within [...] denote character ranges. Thus S-s in regex would mean "every character in Unicode character table between S and s" and as those two are not adjacent, you end up with a bunch of matched chars.

like image 149
Regexident Avatar answered Nov 15 '22 08:11

Regexident


Not answer directly the detail content of the question, but whom who end up to this question by the question's title and looking for the answer of regex to find match words begin with specific letter like : This is a Zone You should use this regex:

\bd[a-zA-Z]+

[a-zA-Z] should replace by the expected tail you want. Take a look at this link

like image 34
chickensoup Avatar answered Nov 15 '22 07:11

chickensoup