// Uncolored, plain source file: deriv3.java // <p> // An example file explaining how to use // com.stevesoft.pat, com.stevesoft.pat.wrap, // and com.stevesoft.pat.apps // <p> // This software comes without express or implied warranty. // No claim is made about the suitability of this software for // any purpose and neither we nor SteveSoft shall be liable for // damages suffered by the user of this software. import com.stevesoft.pat.*;
// This is the new rule we wish to define... // In this case, balanced grouping symbols. // Thus, "({})" will match, and so will "[}".
class Bal extends Validator { public int validate(StringLike src,int start,int end) { // You really shouldn't put print statements here except when // debugging. I'm doing it, however, so you can see what things // validate has to process in the search for a match. System.out.println("validating: >>"+src.substring(0,start)+"|"+ src.substring(start,end)+"|"+src.substring(end,src.length())+"<<"); int count = 0; int m = src.length(); if(m > end) m = end; for(int i=start;i<m;i++) { char c = src.charAt(i); if(c=='('||c=='{'||c=='[') count++; else if(c==')'||c=='}'||c==']') { count--; // We return a match with a different // end position than the variable "end". if(count==0) return i+1; } else if(c=='\\') i++; } return count==0 ? end : -1; } }
public class deriv3 { public static void main(String[] args) { Regex.define( "bal", // name of our new pattern "[([{].*?[\\])}]", // A standard Regex that our pattern must satisfy new Bal()); // Validator for our pattern
// The second argument to Regex is the replacement rule, // and, as is conventional, $& expands to the matched portion // of the pattern. Regex r = new Regex("(??bal)"," *$&* "); // Substitute for valid matches in a test String. String p = r.replaceAll("(hello) {goodbye{world}} (what?[) [see-ya!]"); System.out.println(p); } }