DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Newsletter
Log In / Join
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • Dynamic Arrays, Spill, and LET: What Changed in Excel and Why It Matters for Java Applications
  • Arrays in Java
  • Immutable Objects Using Record in Java
  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems

Trending

  • Member Spotlight: Raghava Dittakavi
  • Part 1: Building Governed MCP Tool Services With Quarkus LangChain4j and Goose
  • Part 2: Securing and Scaling Goose-to-Java Agent Traffic With agentgateway
  • Part 3: End-to-End Tracing and Observability Across Goose, agentgateway, and Quarkus

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

  1. DZone
  2. Data Engineering
  3. Data
  4. Java regex matching hashmap

Java regex matching hashmap

By 
Sutanu Dalui
·
Nov. 07, 14 · Code Snippet
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
23.9K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

 A hashmap which maintains keys as regular expressions. Any pattern matching the expression will be able to retrieve the same value.

Internally it maintains two maps, one containing the regex to value, and another containing matched pattern to regex. Whenever there is a new pattern to 'get', there will be a O(n) search through the compiled regex(s) (which have been 'put' as keys) to find a match. Existing patterns will have constant time lookup through two maps.

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.WeakHashMap;
import java.util.regex.Pattern;


public class RegexHashMap implements Map
{
private class PatternMatcher
{
private final String regex;
private final Pattern compiled;

PatternMatcher(String name)
{
regex = name;
compiled = Pattern.compile(regex);

}

boolean matched(String string)
{
if(compiled.matcher(string).matches())
{
ref.put(string, regex);
return true;
}
return false;
}
}
/**
 * Map of input to pattern
 */
private final Map ref;

/**
 * Map of pattern to value
 */
private final Map map;

/**
 * Compiled patterns
 */
private final List matchers;

@Override
public String toString()
{
return "RegexHashMap [ref=" + ref + ", map=" + map + "]";
}

/**
 * 
 */
public RegexHashMap()
{
ref = new WeakHashMap();
map = new HashMap();
matchers = new ArrayList();
}

/**
 * Returns the value to which the specified key pattern is mapped, or null if this map contains no mapping 
 for the key pattern
 */
@Override
public V get(Object weakKey)
{
if(!ref.containsKey(weakKey))
{
for(PatternMatcher matcher : matchers)
{
if(matcher.matched((String) weakKey))
{
break;
}
}

}
if(ref.containsKey(weakKey))
{
return map.get(ref.get(weakKey));

}
return null;
}

/**
 * Associates a specified regular expression to a particular value
 */
@Override
public V put(String key, V value)
{
V v = map.put(key, value);
if (v == null)
{
matchers.add(new PatternMatcher(key));
}
return v;

}

/**
 * Removes the regular expression key
 */
@Override
public V remove(Object key) 
{
V v = map.remove(key);
if(v != null)
{
for(Iterator iter = matchers.iterator(); iter.hasNext();)
{
PatternMatcher matcher = iter.next();
if(matcher.regex.equals(key))
{
iter.remove();
break;
}
}

for(Iterator> iter = ref.entrySet().iterator(); iter.hasNext();)
{
Entry entry = iter.next();
if(entry.getValue().equals(key))
{
iter.remove();
}
}
}
return v;

    }
/**
 * Set of view on the regular expression keys
 */
@Override
public Set> entrySet()
{
return map.entrySet();
}

@Override
public void putAll(Map m) 
{
for(Entry entry : m.entrySet())
{
put(entry.getKey(), entry.getValue());
}
    }

@Override
public int size()
{
return map.size();
}

@Override
public boolean isEmpty()
{
return map.isEmpty();
}

/**
 * Returns true if this map contains a mapping for the specified regular expression key.
 */
@Override
public boolean containsKey(Object key)
{
return map.containsKey(key);
}

/**
 * Returns true if this map contains a mapping for the specified regular expression matched pattern.
 * @param key
 * @return
 */
public boolean containsKeyPattern(Object key)
{
return ref.containsKey(key);
}

@Override
public boolean containsValue(Object value)
{
return map.containsValue(value);
}

@Override
public void clear()
{
map.clear();
matchers.clear();
ref.clear();
}

/**
 * Returns a Set view of the regular expression keys contained in this map.
 */
@Override
public Set keySet()
{
return map.keySet();
}

/**
 * Returns a Set view of the regex matched patterns contained in this map. The set is backed by the map, so changes to 
 the map are reflected in the set, and vice-versa.
 * @return
 */
public Set keySetPattern()
{
return ref.keySet();
}

@Override
public Collection values()
{
return map.values();
}

/**
 * Produces a map of patterns to values, based on the regex put in this map
 * @param patterns
 * @return
 */
public Map transform(List patterns)
{
for(String pattern : patterns)
{
get(pattern);
}

Map transformed = new HashMap();
for(Entry entry : ref.entrySet())
{
transformed.put(entry.getKey(), map.get(entry.getValue()));
}
return transformed;

}
public static void main(String...strings)
{
RegexHashMap rh = new RegexHashMap();
rh.put("[o|O][s|S][e|E].?[1|2]", "This is a regex match");
rh.put("account", "This is a direct match");
System.out.println(rh);
System.out.println("get:ose-1 -> "+rh.get("ose-1"));
System.out.println("get:OSE2 -> "+rh.get("OSE2"));
System.out.println("get:OSE112 -> "+rh.get("OSE112"));
System.out.println("get:ose-2 -> "+rh.get("ose-2"));
System.out.println("get:account -> "+rh.get("account"));
System.out.println(rh);
}

}
Data structure Java (programming language)

Opinions expressed by DZone contributors are their own.

Related

  • Dynamic Arrays, Spill, and LET: What Changed in Excel and Why It Matters for Java Applications
  • Arrays in Java
  • Immutable Objects Using Record in Java
  • Floyd's Cycle Algorithm for Fraud Detection in Java Systems

Partner Resources

×

Comments

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook