Biểu thức quy tắc regular expression Một biểu thức quy tắc là một kiểu được xác định trong việc tìm kiếm tương ứng các ký tự kết hợp của một chuỗi.. Cú pháp khai báo: có 2 cách var
Trang 1BIỂU THỨC QUY TẮC TRONG
JAVASCRIPT
8/16/2012
1 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT
Trang 2Biểu thức quy tắc (regular expression)
Một biểu thức quy tắc là một kiểu được xác định trong việc tìm kiếm tương ứng các ký tự kết hợp của một chuỗi
ký tự trong một chuỗi nhập vào từ người sử dụng
Cú pháp khai báo: có 2 cách
var object= new RegExp(pattern, attributes);
var object= /pattern/attributes;
Trong đó:
Attributes: các thuộc tính tìm kiếm, gồm có g
(global-tìm tất cả các vị trí), i (không phân biệt hoa thường), m (multiline)
8/16/2012 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT
2
Trang 3Sử dụng biểu thức quy tắc
8/16/2012 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT
3
Biểu thức quy tắc có các phương thức sau:
test: kiểm tra pattern có xuất hiện hay không trả lại kết quả true/false
exec: trả lại giá trị pattern nếu tìm thấy pattern, ngược lại trả lại giá trị null
Cú pháp: variablename=object.method (string);
Các phương thức trên chuỗi được hỗ trợ nhờ biểu thức quy tắc:
match: trả lại mảng lưu các giá trị xuất hiện của pattern
search: Trả lại vị trí tìm thấy (có phân biệt hoa thường)
replace: Thay thế pattern tìm thấy trong chuỗi tìm kiếm bằng một pattern mới
split: Chia chuỗi thành một mảng các chuỗi con
Cú pháp: variable_name=string_name.method (object);
Trang 44
Ví dụ: In ra các giá trị xuất hiện của
pattern
<script>
pattern = /e/g;
str="Time and Tide wait for none"; var arr=str.match(pattern);
for (var i=0; i<arr.length; i++)
document.writeln(i+” “+ arr[i]);
</script>
8/16/2012 ThS.Nguyễn Thị Quỳnh Như-Khoa CNTT
Trang 5Ví dụ Biểu thức quy tắc
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
re = /^T.+e$/;
str = re.test ("Time and Tide wait for none");
window.alert(str);
// cho ket qua false
</SCRIPT>
</HEAD>
</HTML>
8/16/2012 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT
5
Trang 6Ví dụ Biểu thức quy tắc
8/16/2012 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT
6
<HTML>
<HEAD>
<SCRIPT LANGUAGE="JavaScript">
re = /^T.+e$/;
source="Time and Tide wait for none";
str = re.exec (source); // tra lai ket qua la chuoi source da cho
window.alert(str);
re1=/T[a-z]+e/g;
str1=source.match(re1); // str1 la mang luu cac chuoi con tim thay window.alert(str1.length); // do dai mang la 2
window.alert(str1) ; // tra lai ket qua la Time, Tide
</SCRIPT>
</HEAD>
<body>
</body>
</HTML>
Trang 7Ví dụ Biểu thức quy tắc
8/16/2012 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT
7
<script>
pattern = /e/g;
str="Time and Tide wait for
none";
var arr=str.match(pattern);
window.alert(arr.length);
</script>
Trang 88
Brackets (Tìm kiếm theo phạm vi)
Brackets: Brackets are used to find a range of
characters:
[abc] Find any character between the brackets
[^abc] Find any character not between the brackets
[0-9] Find any digit from 0 to 9
[A-Z] Find any character from uppercase A to uppercase Z
[a-z] Find any character from lowercase a to lowercase
[A-z] Find any character from uppercase A to lowercase z
(red|blue|green) Find any of the alternatives specified
8/16/2012 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT
Trang 99
Metacharacters (Các ký tự quy ước đặc biệt)
Metacharacters: Metacharacters are characters with
a special meaning:
MetacharacterDescription
Find a single character, except newline or line terminator
\w Find a word character
\W Find a non-word character
\d Find a digit
\D Find a non-digit character
\s Find a whitespace character
\S Find a non-whitespace character
\b Find a match at the beginning/end of a word
\B Find a match not at the beginning/end of a word
8/16/2012 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT
Trang 10Metacharacters (Các ký tự quy ước đặc biệt)
\0 Find a NULL character
\n Find a new line character
\f Find a form feed character
\r Find a carriage return character
\t Find a tab character
\v Find a vertical tab character
\xxx Find the character specified by an octal number xxx
\xdd Find the character specified by a hexadecimal number dd
\uxxxx Find the Unicode character specified by a hexadecimal number xxxx
10 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT 8/16/2012
Trang 1111
Quantifiers (thành phần lượng hóa)
n+ Matches any string that contains at least one n
n* Matches any string that contains zero or more occurrences of n
n? Matches any string that contains zero or one occurrences of n
n{X} Matches any string that contains a sequence of X n's
n{X,Y} Matches any string that contains a sequence of
X or Y n's
n{X,} Matches any string that contains a sequence of at least X n's
n$ Matches any string with n at the end of it
^n Matches any string with n at the beginning of it
?=n Matches any string that is followed by a specific string n
?!n Matches any string that is not followed by a specific string n
8/16/2012 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT
Trang 12Phương thức match():
match(): Searches for a match between a regular expression and a string, and returns the matches
string.match(regexp)
Example: The phone number field can only contain digits, parenthese, spaces, and hyphens
var reg=/^[-()0-9]+$/;
var reg1=/^[-()0-9]*$/;
Details:
^ match the start of the string
$ match the end of the string
[-()0-9] match any single character that is a hyphen, a parenthesis, a space, or a digit
+ match the longest available string consisting of one or more of the preceding characters
* match zero or more of the preceding characters
12 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT 8/16/2012
Trang 13Ví dụ về check email (1)
Example: Assume that a valid email address must have @ sign and there must be at least one dot”.” at the 4th or 3th
position from the right of the string
var reg =/^.+?@.+?\ {2,3}$/;
^.+ Matches any string with contains at least one single character except newline or line terminator at the beginning of it
^.+? Matches any string that contains zero or one occurrences of ^.+
@.+? Do a global search for a “@", followed by at least one single characters
\ +$ Matches any string with a “.”, followed by at least one single character at the end of it
{2,3} Matches any string with contains at least two or three character
13 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT 8/16/2012
Trang 14Ví dụ về Check email (2)
^: begin with [\w\.-]
[\w\.-] a word character, “.” character, “-” character
^[\w\.-]+: Matches any string with contains at least one [\w\.-] at the beginning of it
@([\w\-]+\.)+: Do a global search for a “@", followed
by at least one([\w\-]+\.)
[a-zA-Z]+$: Matches any string with [a-zA-Z] at the end of it
[a-zA-Z]: Find any character from uppercase A to uppercase Z or find any character from lowercase a to lowercase z
14 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT 8/16/2012
Trang 15Phương thức replace()
replace(): Searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring
string.replace(regexp/substr,newstring)
Details:
regexp/substr: Required A substring or a regular expression
Newstring: Required The string to replace the found value in parameter 1
Example:
<script type="text/javascript“>
var str="Visit Microsoft!";
document.write(str.replace(/microsoft/i, "W3Schools"));
</script>
15 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT 8/16/2012
Trang 16Ví dụ: Check country code
Country code are two letters
var reg=/^[a-zA-Z][a-zA-Z]$/;
[a-zA-Z]: Find any character from uppercase A to uppercase Z or find any character from lowercase a to lowercase z
16 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT 8/16/2012
Trang 17Phương thức search():
search(): Searches for a match between a regular expression and a string, and returns the position of the match
string.search(regexp)
Regexp: Required A regular expression
Example
<script type="text/javascript“>
var str="Visit W3Schools!";
document.write(str.search(/w3schools/i));
</script>
Result :6
17 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT 8/16/2012
Trang 18Phương thức split():
split(): Splits a string into an array of substrings
string.split(separator, limit)
separator Optional: Specifies the character to use for splitting the string If omitted, the entire string will be returned
limit Optional: An integer that specifies the number of splits
Example:
var txt = document.getElementById("txt").value;
var result=document.getElementById("result");
var arr = txt.split("/");
//document.write("<pre>");
for (i=0; i<arr.length;i++)
result.innerText += arr[i]+",";
18 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT 8/16/2012
Trang 19Bài tập áp dụng
Xây dựng form đăng ký và viết lệnh javascript để bắt lỗi form
Trên form có các trường sau:
Tài khoản: Tài khoản có độ dài ít nhất 6 ký tự
Mật khẩu: Mật khẩu phải chứa cả chữ và số
Ngày tháng năm sinh: Ngày tháng năm sinh phải nhỏ hơn ngày tháng năm hiện tại của hệ thống
Email: Email phải đúng định dạng
Câu hỏi ngẫu nhiên và textbox ghi nhận câu trả lời của người sử dụng
Nút Đăng ký: Khi nhấn nút đăng ký thì kiểm tra các yêu cầu trên Nếu dữ liệu không hợp lệ thì yêu cầu nsd nhập lại Nếu
dữ liệu đã hợp lệ thì thông báo đăng ký thành công
Nút Hủy bỏ
8/16/2012
19 ThS.Nguyễn Thị Quỳnh Như.Khoa CNTT