Tuesday, March 2, 2010

Regular Expression Examples

Regex to get Class Name from CSS content:

Regex: \.[-]?[_a-zA-Z][_a-zA-Z0-9-]*|[^\0-\177]*\\[0-9a-f]{1,6}(\r\n[ \n\r\t\f])?|\\[^\n\r\f0-9a-f]*

Input:

.center {text-align: center;}
.smcap {font-variant: small-caps;}
.u {text-decoration: underline;}

#body { ...}

Output:

.center
.smcap
.u

Regex to get all element from CSS content:

Regex: \.[-]?[_a-zA-Z][_a-zA-Z0-9-]*|[^\0-\177]*\\[0-9a-f]{1,6}(\r\n[ \n\r\t\f])?|\\[^\n\r\f0-9a-f]*

Input:

.center {text-align: center;}
.smcap {font-variant: small-caps;}
.u {text-decoration: underline;}
#body { ...}
div.test div.yoyo {...}

Output:

.center
.smcap
.u
#body
div.test div.yoyo

Regex to get HTML element and its content

Regex:

<span\b[^>]*>(.*?)</span>
(wrong in case this: onetwoone).

and

<span\b[^>]*>(?:(?=([^<]+))\1|<(?!table\b[^>]*>))*?</span>

Input:

<p><span><a name="bookmark1" />dirt farmer's son</span></p>

Output:

<span><a name="bookmark1" />dirt farmer's son</span>

No comments: