Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex to check if first 2 characters in a string are Alphabets

I'm new to actionscript and i cant seem to get the regex syntax right in actionscript3. The task is straight forward, i want to make sure that the first two characters in a given string are alphabets and nothing else. Here's what I'm doing and obviously it doesn't work or i wouldn't be here! ;-).

what am I doing wrong here?

var fileName:String = "- Earth"; 
var pattern:RegExp = /(A-Z)(a-z){0,1}/;
if (pattern.test(fileName)) {
   Alert.show("Trew");    
}
else {
   Alert.show("phalse");
}
like image 339
Nesta Avatar asked Jun 10 '11 19:06

Nesta


People also ask

What is difference [] and () in regex?

[] denotes a character class. () denotes a capturing group. [a-z0-9] -- One character that is in the range of a-z OR 0-9.

What does regex 0 * 1 * 0 * 1 * Mean?

Basically (0+1)* mathes any sequence of ones and zeroes. So, in your example (0+1)*1(0+1)* should match any sequence that has 1. It would not match 000 , but it would match 010 , 1 , 111 etc. (0+1) means 0 OR 1.

How do I find a character in a string in regex?

To match a character having special meaning in regex, you need to use a escape sequence prefix with a backslash ( \ ). E.g., \. matches "." ; regex \+ matches "+" ; and regex \( matches "(" . You also need to use regex \\ to match "\" (back-slash).

Which below regex is applicable for alphabets?

[A-Za-z] will match all the alphabets (both lowercase and uppercase).


1 Answers

Not familiar with actionscript, but if it follows normal regex type rules, you need a regex more like:

/^[A-Za-z]{2}/

to match two alpha characters at the start of a string.

like image 136
John Gaines Jr. Avatar answered Oct 06 '22 10:10

John Gaines Jr.