title: String matcher find key value in java
body: <p>My requirement is that I have a given string like
  <code>String originalString = &quot;delhi to goa&quot;;</code></p>
  <p>And I have a string
  <code>String regStr = &quot;%{orgCity} to %{destCity}&quot;;</code></p>
  <p>The given text can be in any format. (Not just &quot;delhi to goa&quot;, it can be &quot;delhi goa to&quot;)</p>
  <p>Now, given these two strings, I want to get a HashMap with key value pair as</p>
  <blockquote>
  <p>orgCity -&gt; delhi</p>
  <p>destCity -&gt; goa</p>
  </blockquote>
  <p>Here key is the string between %{ and } . And value is the corresponding string in the originalString.</p>
  <p>This needs to be implemented using some regex / pattern.</p>
  <p>I could not find the solution for this.</p>
  <p>Can someone help on this??</p>
  <p>Thanks</p>
  <p><strong>Updated</strong></p>
  <p>Solution:</p>
  <pre><code>public static void main(String[] args) {
  
      // Original requirement
      System.out.println(getValueMap(&quot;%{orgCity} to %{destCity}&quot;, &quot;delhi to goa&quot;));
  
      // A variation with two words values
      System.out.println(getValueMap(&quot;%{orgCity} to %{destCity}&quot;, &quot;New York to Mexico&quot;));
  
      // Another variation
      System.out.println(getValueMap(&quot;%{orgCity} to %{destCity} and more&quot;, &quot;delhi to goa and more&quot;));
  
      // order of words doesn't matter
      System.out.println(getValueMap(&quot;%{orgCity} %{destCity} to&quot;, &quot;delhi goa to&quot;));
  
      // different strings than the original requirement
      System.out.println(getValueMap(&quot;I'm going to %{firstCity} and then to %{secondCity}&quot;, &quot;I'm going to Nauru and then to Seattle&quot;));
  
      // more than two values, with more than one word
      System.out.println(getValueMap(&quot;I am %{age} years old, I have %{eyesColour} eyes and %{pocketContent} in my pocket&quot;,
                &quot;I am 20 years old, I have dark blue eyes and two coins in my pocket&quot;));
  
      // etc ...
  }
  
  public static Map&lt;String, String&gt; getValueMap(String format, String text) {
      Map&lt;String, String&gt; map = new HashMap&lt;String, String&gt;();
      String pattern = format;
      String[] keyList = StringUtils.substringsBetween(format, &quot;%{&quot;, &quot;}&quot;);
      for (String str : keyList) {
          pattern = pattern.replaceAll(&quot;\\%\\{&quot; + str + &quot;\\}&quot;, (&quot;(.+)&quot;));
      }
      Pattern r = Pattern.compile(pattern);
  
      Matcher m = r.matcher(text);
      if(!m.find()) {
          throw new RuntimeException(&quot;regStr and originalString don't match&quot;);
      }
      for (int i = 0; i &lt; m.groupCount(); i++) {
          map.put(keyList[i], m.group(i+1));
      }
      return map;
  }
  </code></pre>