Thursday, August 27, 2009

Regular expressions in javascript and Java

Regular expressions lets you to search a text in a text string or do a search and
replace a text in a text string.



Java Script:

Create the expression
================================================================================

var exp = /expression/;
Or
var exp = new RegExp("expression");

Testing availability of a text.
================================================================================

if(/text/.test("The text string.")) alert("Found text");

OR

if ("The text string".match(/text/)) alert("Match found for text");

Doing a search and replace.
================================================================================

var output = "The text string".replace(/text/g, "replacement");

OR

var re = new RegExp("text", "g");
var output = "The text string".replace(re,"replacement");

Using the /g OR "g" modifier makes sure that all occurrences of "text" are replaced


Splitting a text string by a delimiter
================================================================================

var myArray = "comma, separated, text, string".split(/,/);


Retrieving the part of the string that was matched
================================================================================

var mymatch = /text/.exec("The text string")

if (mymatch == null) {
alert("No match");
} else {
var s = "Match at position " + mymatch .index + ":\n";
for (i = 0; i < s =" s" mystringarr = "comma, separated, text, string" replaced = "change, delimiter, of, text, string" regex = "match this string" regex = "match.*" class ="=" mypattern =" Pattern.compile(" mymatcher =" myPattern.matcher("> The "^" says check the beginning of the text. [A-Z] specify range of
numbers.

Check for any text starting with a digit 1 to 5.
==============================================================================

^[1-5]

See reference [http://www.regular-expressions.info/reference.html] for details.

No comments:

Post a Comment

Subscribe