Two-way string matching with wildcard characters on both sides in java
<p>I have a situation where I have a list of 8 character-long strings containing wildcard characters (represented by <code>?</code>), that I need to match to an input string that also has wildcard characters. Said string is composed of four alphabetic characters (A-Z) followed by four numbers (0-9). To make it easier to understand, here's an example of a set of strings:</p>

<pre><code>ABCD1234
A??D123?
A???????
?BC1234?
</code></pre>

<p>If I give <code>A?CD12?4</code> as input, the comparison should resolve to true in every comparison. </p>

<p>My current implementation is using Hashmap, using the string as key and the same string parsed as regex as the object mapped. For instance <code>A?CD12?4</code> becomes <code>A([A-Z]|\\?)CD12([0-9]|\\?)4</code>, and then using the following code to obtain a set of the compatible strings:</p>

<pre><code>Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();

map.put("A???????", "A([A-Z]|\\?)([A-Z]|\\?)([A-Z]|\\?)([0-9]|\\?)([0-9]|\\?)([0-9]|\\?)([0-9]|\\?)");
map.put("ABCD1234", "ABCD1234");
map.put("A??D123?", "A([A-Z]|\\?)([A-Z]|\\?)D123([0-9]|\\?)");
map.put("?BCD123?", "([A-Z]|\\?)BC123([0-9]|\\?)");


String str = "A?CD12?4";
String strReg = "A([A-Z]|\\?)CD12([0-9]|\\?)4";

Set&lt;Object&gt; set = map.keySet()
               .stream()
               .filter(s -&gt; str.matches(map.get(s)) || s.matches(strReg) )
               .collect(Collectors.toSet());
</code></pre>

<p>However, this still missed inputs where a wildcard question mark in <code>str</code> but not on the map string (for instance, the input <code>A?CD1234</code> would not resolve as true for <code>?BCD1234</code> and vice-versa).</p>

<p>While I know this would be trivial to fix by iterating over the String, my solution requires the input to be compared to over <strong>50000</strong> Strings, and I read inputs at a rate of around <strong>30/second</strong>, so performance is key.</p>

<p>This processing happens inside a Thread, and outside interaction can change the list of strings the input will check (add or remove only).</p>