Regular Expression
special characters
|
\
|
Toggles between literal and special characters |
| ^ |
Beginning of a string |
| $ |
End of a string |
| * |
Zero or more times |
| + |
One or more times |
| ? |
Zero or one time |
| . |
Any character except newline |
| \b |
Word boundary |
| \B |
Non-word boundary |
| \d |
Any digit 0 - 9 |
| \D |
Any non-digit |
| \f |
Form feed |
| \n |
New line |
| \r |
Carriage return |
| \s |
Any single white space |
| \S |
Any sing non-white space character |
| \t |
Tab |
| \v |
Vertical Tab |
| \w |
Any Letter, number or the underscore |
| \W |
Any character other than a letter, number or underscore |
| \xnn |
hexadecimal number |
| \onn |
octal number |
| \cX |
control character X |
| [abcde] |
Character set that matches one of the enclosed characters |
| [^abcde] |
Character set that does not match one of the enclosed
characters |
| [a-e] |
A character set that matches any one in the range of
enclosed characters |
| [\b] |
Backspace character |
{n}
|
Exactly n occurrences of the previous character |
| {n,} |
At least n occurrences of the previous character |
| {n,m} |
Between n and m occurrences of the previous character |
| () |
A grouping, which is also stored |
| x|y |
Either X or Y |
| |
| Modifiers |
| g |
Search for all possible mathces |
| i |
Search without case-sensitivity |
Validating an email address with regular expressions
<script>
re = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/
function submitIt(form) {
if (re.test(form.emailAddr.value)) {
return true
}
alert("Invalid email address")
form.emailAddr.focus()
form.emailAddr.select()
return false
}
</script>
<body>
<form onsubmit="return submitIt(this)" action="somepage.cgi">
<p>email address:
<input type="text" name="emailAddr">
<input type="submit" value="submit">
</p>
</form>
</body>
Validating an image file with regular expressions
<script>
re = /^(file|http):\/\/\S+\/\S+\.(gif|jpg)$/i
function submitIt(form) {
if (re.test(form.imgURL.value)) {
document.chgImg.src = form.imgURL.value
}
else {
alert("Invalid URL ")
form.imgURL.focus()
form.imgURL.select()
}
return false
}
</script>
<body>
<form onsubmit="return submitIt(this)" action="somepage.cgi">
<p>Image URL :
<input type="text" name="imgURL" size="50">
<input type="submit" value="submit">
</p>
<p>
<img src="" name="chgImg"
</p>
</form>
</body>
Formatting and Validating Strings
<script>
re = /^\(?(\d{3})\)?[\.\-\/ ]?(\d{3})[\.\-\/ ]?(\d{4})$/
function submitIt(form) {
validPhone = re.exec(form.phone.value)
if (validPhone) {
form.phone.value = "(" + validPhone[1] + ") " + validPhone[2]
+ "-" + validPhone[3]
}
else {
alert(form.phone.value + " isn't a vlaid phone number")
form.phone.focus()
form.phone.select()
}
return false
}
</script>
<body>
<form onsubmit="return submitIt(this)" >
<p>Phone Number (with area code): <input name="phone" type="text"> <input
type="submit" value="submit">
</p>
</form>
</body>
|