{"id":50,"date":"2004-10-21T22:06:24","date_gmt":"2004-10-21T12:06:24","guid":{"rendered":"http:\/\/thekua.com\/rant\/?p=50"},"modified":"2012-04-01T10:12:21","modified_gmt":"2012-04-01T09:12:21","slug":"optimising-java-regular-expressions","status":"publish","type":"post","link":"https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/","title":{"rendered":"Optimising Java Regular Expressions"},"content":{"rendered":"<p>Yesterday I had a bit of interesting work performancing tuning some code for our project&#8217;s current iteration. The code that required optimisation basically filtered some results in memory based on a set of user-specified criteria. The criteria contained a variety of different datatypes (boolean, numeric and string) and my suspicions were confirmed after a bit of simplistic profiling that the biggest consumer of computation time was the string pattern matching that was being performed.<\/p>\n<p>So here are a few tips for optimising Regular Expression usage in the Java langauge:<!--more--><\/p>\n<ol>\n<li><strong>Minimise the number of times a regular expression is compiled (preferrably statically at source compilation time):<\/strong> <br \/>Take this code as an example and note that the pattern should be moved outside of the loop:\n<p><code>&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;public List getMatchingValues(&lt;br \/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;String [] extremelyLongListOfValuesForComparison, String stringToMatchOn) {&lt;br \/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;List listOfMatchingStrings = new ArrayList(extremelyLongListOfValuesForComparison.length);&lt;br \/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;for (int i = 0; i &lt; extremelyLongListOfValuesForComparison.length; i++ ) {&lt;br\/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;\/\/ !!! This pattern should be initialised outside of the loop&lt;br \/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;Pattern pattern = Pattern.compile(stringToMatchOn + \".*\"); &lt;br \/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;if (pattern.matcher(extremelyLongListOfValuesForComparison[i]).matches()) {&lt;br \/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;listOfMatchingStrings.add(extremelyLongListOfValuesForComparison[i]);&lt;br \/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br \/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;br \/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;return listOfMatchingStrings;&lt;br \/&gt;&amp;nbsp;&amp;nbsp;&amp;nbsp;&amp;nbsp;}&lt;\/&gt;<\/code>\n       <\/li>\n<li><strong>Be aware of libraries and the JDK where convenience methods compile their own Pattern instances. <\/strong>\n<p>Many useful <a href=\"http:\/\/docs.oracle.com\/javase\/6\/docs\/api\/java\/lang\/String.html\">java.lang.String<\/a> operations in the JDK use it for example (and is well documented). These include <a href=\"http:\/\/docs.oracle.com\/javase\/6\/docs\/api\/java\/lang\/String.html#matches(java.lang.String)\">matches<\/a>, <a href=\"http:\/\/docs.oracle.com\/javase\/6\/docs\/api\/java\/lang\/String.html#replaceAll(java.lang.String, java.lang.String)\">replaceAll<\/a>, <a href=\"http:\/\/docs.oracle.com\/javase\/6\/docs\/api\/java\/lang\/String.html#replaceFirst(java.lang.String, java.lang.String)\">replaceFirst<\/a>, and <a href=\"http:\/\/docs.oracle.com\/javase\/6\/docs\/api\/java\/lang\/String.html#split(java.lang.String)\">split<\/a>.<\/p>\n<li><strong>Prefer Matcher.find() over Matcher.matches() if you can. <\/strong>\n<p>Think of the situation where you are looking for two words that appear in a sentence in order. On initial thought, a regular expression like, <code>\".*two.*words.*\"<\/code>, might jump to mind, of which you would instantiate a matcher and call the <a href=\"http:\/\/docs.oracle.com\/javase\/6\/docs\/api\/java\/util\/regex\/Matcher.html#matches()\">matches()<\/a> operation. We actually found that simplifying the regular expression to <code>\"two.*words\"<\/code>, creating a matcher and then calling the <a href=\"http:\/\/docs.oracle.com\/javase\/6\/docs\/api\/java\/util\/regex\/Matcher.html#find()\">find()<\/a> operation increased performance significantly.\n<\/li>\n<li><strong>Construct your Regular Expressions carefully when you need to ignore whitespace.<\/strong>\n<p>   For the above scenario, a user could enter several words to find any matches (in order) against a given string. Our initial code in constructing the string for the pattern was something like:<\/p>\n<p><code>\/\/ replace any space with a wildcard match on any string in between<\/code><br \/>\n<code>searchPatternString = searchTermString.replace(\" \", \".*\"); <\/code><\/p>\n<p>After a bit of testing though, a string like <code>\"find&amp;nbsp;&amp;nbsp;me\"<\/code> (note the two spaces) resulted in a pattern that would have looked like <code>\"find.*.*me\"<\/code>. One might expect that when the pattern was compiled, it could have been internally optimised to an equivalent pattern <code>\"find.*me\"<\/code> but apparently did not. A better revised pattern was thus developed using <code>\"\\s*\"<\/code> (any and all white space characters) and of course, rule number 1 was applied afterwards.<\/li>\n<\/li>\n<\/ol>\n","protected":false},"excerpt":{"rendered":"<p>Yesterday I had a bit of interesting work performancing tuning some code for our project&#8217;s current iteration. The code that required optimisation basically filtered some results in memory based on a set of user-specified criteria. The criteria contained a variety of different datatypes (boolean, numeric and string) and my suspicions were confirmed after a bit [&hellip;]<\/p>\n","protected":false},"author":3,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[3],"tags":[39],"class_list":["post-50","post","type-post","status-publish","format-standard","hentry","category-technical","tag-work-related"],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v28.8 - https:\/\/yoast.com\/product\/yoast-seo-wordpress\/ -->\n<title>Optimising Java Regular Expressions - thekua.com@rest<\/title>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"Optimising Java Regular Expressions - thekua.com@rest\" \/>\n<meta property=\"og:description\" content=\"Yesterday I had a bit of interesting work performancing tuning some code for our project&#8217;s current iteration. The code that required optimisation basically filtered some results in memory based on a set of user-specified criteria. The criteria contained a variety of different datatypes (boolean, numeric and string) and my suspicions were confirmed after a bit [&hellip;]\" \/>\n<meta property=\"og:url\" content=\"https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/\" \/>\n<meta property=\"og:site_name\" content=\"thekua.com@rest\" \/>\n<meta property=\"article:published_time\" content=\"2004-10-21T12:06:24+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2012-04-01T09:12:21+00:00\" \/>\n<meta name=\"author\" content=\"Patrick\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Patrick\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"3 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\\\/\\\/schema.org\",\"@graph\":[{\"@type\":\"Article\",\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/2004\\\/10\\\/optimising-java-regular-expressions\\\/#article\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/2004\\\/10\\\/optimising-java-regular-expressions\\\/\"},\"author\":{\"name\":\"Patrick\",\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/#\\\/schema\\\/person\\\/6de103b28f96be3f1f4dc25db357c6ae\"},\"headline\":\"Optimising Java Regular Expressions\",\"datePublished\":\"2004-10-21T12:06:24+00:00\",\"dateModified\":\"2012-04-01T09:12:21+00:00\",\"mainEntityOfPage\":{\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/2004\\\/10\\\/optimising-java-regular-expressions\\\/\"},\"wordCount\":349,\"commentCount\":0,\"publisher\":{\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/#\\\/schema\\\/person\\\/6de103b28f96be3f1f4dc25db357c6ae\"},\"keywords\":[\"Work-Related\"],\"articleSection\":[\"Work Related\"],\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"CommentAction\",\"name\":\"Comment\",\"target\":[\"https:\\\/\\\/thekua.com\\\/rant\\\/2004\\\/10\\\/optimising-java-regular-expressions\\\/#respond\"]}]},{\"@type\":\"WebPage\",\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/2004\\\/10\\\/optimising-java-regular-expressions\\\/\",\"url\":\"https:\\\/\\\/thekua.com\\\/rant\\\/2004\\\/10\\\/optimising-java-regular-expressions\\\/\",\"name\":\"Optimising Java Regular Expressions - thekua.com@rest\",\"isPartOf\":{\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/#website\"},\"datePublished\":\"2004-10-21T12:06:24+00:00\",\"dateModified\":\"2012-04-01T09:12:21+00:00\",\"breadcrumb\":{\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/2004\\\/10\\\/optimising-java-regular-expressions\\\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\\\/\\\/thekua.com\\\/rant\\\/2004\\\/10\\\/optimising-java-regular-expressions\\\/\"]}]},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/2004\\\/10\\\/optimising-java-regular-expressions\\\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\\\/\\\/thekua.com\\\/rant\\\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"Optimising Java Regular Expressions\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/#website\",\"url\":\"https:\\\/\\\/thekua.com\\\/rant\\\/\",\"name\":\"thekua.com@rest\",\"description\":\"\",\"publisher\":{\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/#\\\/schema\\\/person\\\/6de103b28f96be3f1f4dc25db357c6ae\"},\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\\\/\\\/thekua.com\\\/rant\\\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":[\"Person\",\"Organization\"],\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/#\\\/schema\\\/person\\\/6de103b28f96be3f1f4dc25db357c6ae\",\"name\":\"Patrick\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/wp-content\\\/uploads\\\/2025\\\/12\\\/pat-kua-head.png\",\"url\":\"https:\\\/\\\/thekua.com\\\/rant\\\/wp-content\\\/uploads\\\/2025\\\/12\\\/pat-kua-head.png\",\"contentUrl\":\"https:\\\/\\\/thekua.com\\\/rant\\\/wp-content\\\/uploads\\\/2025\\\/12\\\/pat-kua-head.png\",\"width\":400,\"height\":400,\"caption\":\"Patrick\"},\"logo\":{\"@id\":\"https:\\\/\\\/thekua.com\\\/rant\\\/wp-content\\\/uploads\\\/2025\\\/12\\\/pat-kua-head.png\"},\"sameAs\":[\"http:\\\/\\\/www.thekua.com\"],\"url\":\"https:\\\/\\\/thekua.com\\\/rant\\\/author\\\/patrick\\\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"Optimising Java Regular Expressions - thekua.com@rest","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/","og_locale":"en_US","og_type":"article","og_title":"Optimising Java Regular Expressions - thekua.com@rest","og_description":"Yesterday I had a bit of interesting work performancing tuning some code for our project&#8217;s current iteration. The code that required optimisation basically filtered some results in memory based on a set of user-specified criteria. The criteria contained a variety of different datatypes (boolean, numeric and string) and my suspicions were confirmed after a bit [&hellip;]","og_url":"https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/","og_site_name":"thekua.com@rest","article_published_time":"2004-10-21T12:06:24+00:00","article_modified_time":"2012-04-01T09:12:21+00:00","author":"Patrick","twitter_card":"summary_large_image","twitter_misc":{"Written by":"Patrick","Est. reading time":"3 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"Article","@id":"https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/#article","isPartOf":{"@id":"https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/"},"author":{"name":"Patrick","@id":"https:\/\/thekua.com\/rant\/#\/schema\/person\/6de103b28f96be3f1f4dc25db357c6ae"},"headline":"Optimising Java Regular Expressions","datePublished":"2004-10-21T12:06:24+00:00","dateModified":"2012-04-01T09:12:21+00:00","mainEntityOfPage":{"@id":"https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/"},"wordCount":349,"commentCount":0,"publisher":{"@id":"https:\/\/thekua.com\/rant\/#\/schema\/person\/6de103b28f96be3f1f4dc25db357c6ae"},"keywords":["Work-Related"],"articleSection":["Work Related"],"inLanguage":"en-US","potentialAction":[{"@type":"CommentAction","name":"Comment","target":["https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/#respond"]}]},{"@type":"WebPage","@id":"https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/","url":"https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/","name":"Optimising Java Regular Expressions - thekua.com@rest","isPartOf":{"@id":"https:\/\/thekua.com\/rant\/#website"},"datePublished":"2004-10-21T12:06:24+00:00","dateModified":"2012-04-01T09:12:21+00:00","breadcrumb":{"@id":"https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/"]}]},{"@type":"BreadcrumbList","@id":"https:\/\/thekua.com\/rant\/2004\/10\/optimising-java-regular-expressions\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/thekua.com\/rant\/"},{"@type":"ListItem","position":2,"name":"Optimising Java Regular Expressions"}]},{"@type":"WebSite","@id":"https:\/\/thekua.com\/rant\/#website","url":"https:\/\/thekua.com\/rant\/","name":"thekua.com@rest","description":"","publisher":{"@id":"https:\/\/thekua.com\/rant\/#\/schema\/person\/6de103b28f96be3f1f4dc25db357c6ae"},"potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/thekua.com\/rant\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":["Person","Organization"],"@id":"https:\/\/thekua.com\/rant\/#\/schema\/person\/6de103b28f96be3f1f4dc25db357c6ae","name":"Patrick","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/thekua.com\/rant\/wp-content\/uploads\/2025\/12\/pat-kua-head.png","url":"https:\/\/thekua.com\/rant\/wp-content\/uploads\/2025\/12\/pat-kua-head.png","contentUrl":"https:\/\/thekua.com\/rant\/wp-content\/uploads\/2025\/12\/pat-kua-head.png","width":400,"height":400,"caption":"Patrick"},"logo":{"@id":"https:\/\/thekua.com\/rant\/wp-content\/uploads\/2025\/12\/pat-kua-head.png"},"sameAs":["http:\/\/www.thekua.com"],"url":"https:\/\/thekua.com\/rant\/author\/patrick\/"}]}},"_links":{"self":[{"href":"https:\/\/thekua.com\/rant\/wp-json\/wp\/v2\/posts\/50","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/thekua.com\/rant\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/thekua.com\/rant\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/thekua.com\/rant\/wp-json\/wp\/v2\/users\/3"}],"replies":[{"embeddable":true,"href":"https:\/\/thekua.com\/rant\/wp-json\/wp\/v2\/comments?post=50"}],"version-history":[{"count":7,"href":"https:\/\/thekua.com\/rant\/wp-json\/wp\/v2\/posts\/50\/revisions"}],"predecessor-version":[{"id":2876,"href":"https:\/\/thekua.com\/rant\/wp-json\/wp\/v2\/posts\/50\/revisions\/2876"}],"wp:attachment":[{"href":"https:\/\/thekua.com\/rant\/wp-json\/wp\/v2\/media?parent=50"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/thekua.com\/rant\/wp-json\/wp\/v2\/categories?post=50"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/thekua.com\/rant\/wp-json\/wp\/v2\/tags?post=50"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}