Tuesday, October 6, 2015

Java Regex


Putting this up for my own reference more than any other reason. Java Regex are useful in manipulation strings. A regex consist of pattern blocks and optional quantifiers.


Pattern Blocks


some patterns are built in to java,

\d - digit
\w – word character
\s – whitespace

if a range of characters need to be used as a pattern it should be put as follows,

[a-z] – a to z simple
[a-zA-Z] - a to z capital and simple
[1-9] – 1 to 9

Quantifiers


these add meaning to the patterns. They should be added immediately after the pattern.

* - match pattern 0 or more times
+ - match pattern 1 or more times
{n} - match pattern exactly n times
{n,m} – match pattern between n to m times


Regex Examples


[a-zA-Z]* - a to z capital and simple 0 or more times
[a-zA-Z]+ - a to z capital and simple 1 or more times
\d{2,5} – digits 2 to 5 times
[.]*[a-zA-Z]{1,5} - . 0 or more times in the beginning followed by a to z capital and simple 1 to 5 time, the whole pattern once. 

No comments:

Post a Comment

What's in my Bag? EDC of a Tester