[Solved] Recognizing a pattern for regular expressions [closed]


In Java there are lots of ways you can code to get the contents between brackets (or any two specific characters for that matter) but you sort of want to dabble with a regular expression which can be rather slow for this sort of thing especially when dealing with multiple instances of bracket pairs within a supplied string.

The basic code you want to gather up the contents contained between Curly Brackets could be something like this:

String myString = "something + {SomeProductSet1}.count + {SomeOtherProductSet2}.amount > \n" +
                "    {SomeProductSet3}.count + {SomeUSOC4}.amount";
Matcher match = Pattern.compile("\\{([^}]+)\\}").matcher(myString);
while(match.find()) {
    System.out.println(match.group(1));    
}

What the above Regular Expression means:

  • \\{ Open Curly Bracket character {
  • ( start match group
  • [ one of these characters
  • ^ not the following character
  • } with the previous ^, this means “every character except the Close
    Curly Bracket }
  • + one of more other characters from the [] set
  • ) stop match group
  • \\} literal Closing Curly Bracket }

If it were me, I would create a method to house this code so that it can be used for other bracket types as well like: Parentheses (), Square Brackets [], Curly Brackets {} (as shown in code), Chevron Brackets <>, or even between any two supplied characters like: /…/ or %…% or maybe even A…A. See the example method below which demonstrates this.

In the example code above it would be within the while loop where you would handle each substring found between each set of brackets. You will of course require a mechanism to determine which substring detected is to be replaced with whatever string like perhaps a multidimensional Array, or perhaps even a custom dialog which would display the found substring between each bracket and allow the User to select its replacement from perhaps a Combo Box with a Do All option Check Box. There are of course several options here for how and what you want to handle each found substring between each set of brackets.

Here is a method example which demonstrates what we’ve discussed here. It is well commented:

public String replaceBetween(String inputString, String openChar, 
                             String closeChar, String[][] replacements) {
    // If the supplied input String contains nothing
    // then return a Null String ("").
    if (inputString.isEmpty()) { return ""; }

    // Declare a string to hold the input string, this way
    // we can freely manipulate it without jeopordizing the
    // original input string.
    String inString = inputString;

    // Set the escape character (\) for RegEx special Characters
    // for both the openChar and closeChar parameters in case
    // a character in each was supplied that is a special RegEx
    // character. We'll use RegEx to do this.
    Pattern regExChars = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");
    String opnChar = regExChars.matcher(openChar).replaceAll("\\\\$0");
    String clsChar = regExChars.matcher(closeChar).replaceAll("\\\\$0");

    // Create our Pattern to find the items contained between
    // the characters tht was supplied in the openChar and
    // closeChar parameters.
    Matcher m = Pattern.compile(opnChar + "([^" + closeChar + "]+)" + clsChar).matcher(inString);

    // Iterate through the located items...
    while(m.find()) {
        String found = m.group(1);
        // Lets see if the found item is contained within
        // our supplied 2D replacement items Array... 
        for (int i = 0; i < replacements.length; i++) {
            // Is an item found in the array?
            if (replacements[i][0].equals(found)) {
                // Yup... so lets replace the found item in our 
                // input string with the related element in our
                // replacement array.
                inString = inString.replace(openChar + found + closeChar, replacements[i][1]);
            }
        }
    }
    // Return the modified input string.
    return inString;
}

To use this method you might do this:

// Our 2D replacement array. In the first column we place 
// the substrings we would like to find within our input 
// string and in the second column we place what we want 
// to replace the item in the first column with if it's 
// found.
String[][] replacements = {{"SomeProductSet1", "[abc]"}, 
                           {"SomeOtherProductSet2", "[xyz]"},
                           {"SomeProductSet3", "[xom]"},
                           {"SomeUSOC4", "[ytkd]"}};

// The string we want to modify (the input string):
String example = "something + {SomeProductSet1}.count + {SomeOtherProductSet2}.amount > \n" +
                 "    {SomeProductSet3}.count + {SomeUSOC4}.amount";

// Lets make the call and place the returned result
// into a new variable...
String newString = replaceBetween(example, "{", "}", replacements);

// Display the new string variable contents
// in Console.
System.out.println(newString);

The Console should display:

something + [abc].count + [xyz].amount > 
    [xom].count + [ytkd].amount

Notice how it also replaces the Curly Brackets? This appears to be one of your requirements but can be easily modified to just replace the substring between the brackets. Perhaps you can modify this method (if you like) to do this optionally and as yet another added optional feature….allow it to ignore letter case.

1

solved Recognizing a pattern for regular expressions [closed]