Example usage for java.util.regex Pattern compile

List of usage examples for java.util.regex Pattern compile

Introduction

In this page you can find the example usage for java.util.regex Pattern compile.

Prototype

public static Pattern compile(String regex) 

Source Link

Document

Compiles the given regular expression into a pattern.

Usage

From source file:com.opengamma.bbg.loader.BloombergSwaptionFileLoader.java

/**
 * Little util to parse swaption tickers into a csv for further analysis.
 * @param args command line params/*from ww  w  . j a  va  2 s  .c  om*/
 */
public static void main(String[] args) { // CSIGNORE
    CSVReader csvReader = null;
    CSVWriter csvWriter = null;
    try {
        csvReader = new CSVReader(new BufferedReader(new FileReader(args[0])));
        csvWriter = new CSVWriter(new BufferedWriter(new FileWriter(args[1])));
        String[] line;
        Pattern pattern = Pattern.compile("^(\\w\\w\\w).*?(\\d+)(M|Y)(\\d+)(M|Y)\\s*?(PY|RC)\\s*?(.*)$");
        BloombergReferenceDataProvider rawBbgRefDataProvider = getBloombergSecurityFileLoader();
        MongoDBValueCachingReferenceDataProvider bbgRefDataProvider = MongoCachedReferenceData
                .makeMongoProvider(rawBbgRefDataProvider, BloombergSwaptionFileLoader.class);
        while ((line = csvReader.readNext()) != null) {
            String name = line[NAME_FIELD];
            Matcher matcher = pattern.matcher(name);
            if (matcher.matches()) {
                String ccy = matcher.group(1);
                String swapTenorSize = matcher.group(2);
                String swapTenorUnit = matcher.group(3);
                String optionTenorSize = matcher.group(4);
                String optionTenorUnit = matcher.group(5);
                String payReceive = matcher.group(6);
                String distanceATM = matcher.group(7);

                String buid = "/buid/" + line[BUID_FIELD];
                String value = bbgRefDataProvider.getReferenceDataValue(buid, "TICKER");
                csvWriter.writeNext(new String[] { name, ccy, swapTenorSize, swapTenorUnit, optionTenorSize,
                        optionTenorUnit, payReceive, distanceATM, value });
            } else {
                s_logger.error("Couldn't parse " + name + " field");
            }

        }
    } catch (IOException ioe) {
        s_logger.error("Error while reading file", ioe);
    } finally {
        IOUtils.closeQuietly(csvReader);
        IOUtils.closeQuietly(csvWriter);
    }
}

From source file:RESimple.java

public static void main(String[] argv) {
    String pattern = "^Q[^u]\\d+\\.";
    String input = "QA777. is the next flight. It is on time.";

    Pattern p = Pattern.compile(pattern);

    boolean found = p.matcher(input).lookingAt();

    System.out.println("'" + pattern + "'" + (found ? " matches '" : " doesn't match '") + input + "'");
}

From source file:Grep0.java

public static void main(String[] args) throws IOException {
    BufferedReader is = new BufferedReader(new InputStreamReader(System.in));
    if (args.length != 1) {
        System.err.println("Usage: MatchLines pattern");
        System.exit(1);//from   w  w  w  .  j  a  v  a  2s . c  o  m
    }
    Pattern patt = Pattern.compile(args[0]);
    Matcher matcher = patt.matcher("");
    String line = null;
    while ((line = is.readLine()) != null) {
        matcher.reset(line);
        if (matcher.find()) {
            System.out.println("MATCH: " + line);
        }
    }
}

From source file:GrepNIO.java

public static void main(String[] args) throws IOException {

    if (args.length < 2) {
        System.err.println("Usage: GrepNIO patt file [...]");
        System.exit(1);/*from w  w  w.ja  v  a2 s.co m*/
    }

    Pattern p = Pattern.compile(args[0]);
    for (int i = 1; i < args.length; i++)
        process(p, args[i]);
}

From source file:NLMatch.java

public static void main(String[] argv) {

    String input = "I dream of engines\nmore engines, all day long";
    System.out.println("INPUT: " + input);
    System.out.println();/* www. j  a  v a  2 s.  c o m*/

    String[] patt = { "engines.more engines", "engines$" };

    for (int i = 0; i < patt.length; i++) {
        System.out.println("PATTERN " + patt[i]);

        boolean found;
        Pattern p1l = Pattern.compile(patt[i]);
        found = p1l.matcher(input).find();
        System.out.println("DEFAULT match " + found);

        Pattern pml = Pattern.compile(patt[i], Pattern.DOTALL | Pattern.MULTILINE);
        found = pml.matcher(input).find();
        System.out.println("MultiLine match " + found);
        System.out.println();
    }
}

From source file:ReplaceDemo.java

public static void main(String[] argv) {

    // Make an RE pattern to match almost any form (deamon, demon, etc.).
    String patt = "d[ae]{1,2}mon"; // i.e., 1 or 2 'a' or 'e' any combo

    // A test input.
    String input = "Unix hath demons and deamons in it!";
    System.out.println("Input: " + input);

    // Run it from a RE instance and see that it works
    Pattern r = Pattern.compile(patt);
    Matcher m = r.matcher(input);
    System.out.println("ReplaceAll: " + m.replaceAll("daemon"));

    // Show the appendReplacement method
    m.reset();//from w  ww .j ava  2  s. c o  m
    StringBuffer sb = new StringBuffer();
    System.out.print("Append methods: ");
    while (m.find()) {
        m.appendReplacement(sb, "daemon"); // Copy to before first match,
        // plus the word "daemon"
    }
    m.appendTail(sb); // copy remainder
    System.out.println(sb.toString());
}

From source file:eu.annocultor.converters.geonames.GeonamesDumpToRdf.java

public static void main(String[] args) throws Exception {
    File root = new File("input_source");

    // load country-continent match
    countryToContinent//from w  w w .ja  v a  2s .c o m
            .load((new GeonamesDumpToRdf()).getClass().getResourceAsStream("/country-to-continent.properties"));

    // creating files
    Map<String, BufferedWriter> files = new HashMap<String, BufferedWriter>();
    Map<String, Boolean> started = new HashMap<String, Boolean>();

    for (Object string : countryToContinent.keySet()) {
        String continent = countryToContinent.getProperty(string.toString());
        File dir = new File(root, continent);
        if (!dir.exists()) {
            dir.mkdir();
        }
        files.put(string.toString(), new BufferedWriter(new OutputStreamWriter(
                new FileOutputStream(new File(root, continent + "/" + string + ".rdf")), "UTF-8")));
        System.out.println(continent + "/" + string + ".rdf");
        started.put(string.toString(), false);
    }

    System.out.println(started);

    Pattern countryPattern = Pattern
            .compile("<inCountry rdf\\:resource\\=\"http\\://www\\.geonames\\.org/countries/\\#(\\w\\w)\"/>");
    long counter = 0;
    LineIterator it = FileUtils.lineIterator(new File(root, "all-geonames-rdf.txt"), "UTF-8");
    try {
        while (it.hasNext()) {
            String text = it.nextLine();
            if (text.startsWith("http://sws.geonames"))
                continue;

            // progress
            counter++;
            if (counter % 100000 == 0) {
                System.out.print("*");
            }
            //         System.out.println(counter);
            // get country
            String country = null;
            Matcher matcher = countryPattern.matcher(text);
            if (matcher.find()) {
                country = matcher.group(1);
            }
            //         System.out.println(country);
            if (country == null)
                country = "null";
            text = text.replace("<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"no\"?><rdf:RDF",
                    "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><rdf:RDF");
            if (started.get(country) == null)
                throw new Exception("Unknow country " + country);
            if (started.get(country).booleanValue()) {
                // remove RDF opening
                text = text.substring(text.indexOf("<rdf:RDF "));
                text = text.substring(text.indexOf(">") + 1);
            }
            // remove RDF ending
            text = text.substring(0, text.indexOf("</rdf:RDF>"));
            files.get(country).append(text + "\n");
            if (!started.get(country).booleanValue()) {
                // System.out.println("Started with country " + country);
            }
            started.put(country, true);
        }
    } finally {
        LineIterator.closeQuietly(it);
    }

    for (Object string : countryToContinent.keySet()) {
        boolean hasStarted = started.get(string.toString()).booleanValue();
        if (hasStarted) {
            BufferedWriter bf = files.get(string.toString());
            bf.append("</rdf:RDF>");
            bf.flush();
            bf.close();
        }
    }
    return;
}

From source file:com.payne.test.StringTest.java

public static void main(String[] args) throws IOException {
    //        String a = "160504185452148809-1";
    //        a = a.split("-")[0];
    //        System.out.println(a);
    //        Random r = new Random();
    //        long a = 0l;
    //        for(int i=0;i<10000;i++){
    //            a = r.nextInt(5001) + 5000;
    //            if(a==5000){
    //                System.out.println(a);
    //            }
    //        }/* w  w  w . ja va  2s . c o  m*/

    /**
     * ????
     */
    //        List<Integer> numberList = new ArrayList<>();
    //        numberList.add(1);
    //        numberList.add(2);
    //        Integer[] numbers = numberList.toArray(new Integer[numberList.size()]);
    ////        int[] numbers = new int[]{1,2};
    //        
    //        System.out.println(new Integer[]{}.length==0?0:1);
    //        
    //        Student s =  new Student();
    //        s.sumUp(new Integer[]{}.length==0?numbers:new Integer[]{1});
    //        s.sumUp(numbers);
    //        Parent p = null;
    //        Parent p2 = new Parent(new Student(5));
    //
    //        Student s = new Student();
    //        p = s.print(p);

    //        System.out.println(p==null?0:1);
    //        System.out.println(p.getAge());
    //        System.out.println(p.getStudent().getAge());
    //        int ai = 0;
    //        for(int i=0;i<2;i++){
    //            int b = 0;
    //            int b_grow = 0;
    //            for(int j=0;j<5;j++){
    //                b += new Random().nextInt(5);
    //            }
    //            
    //        }
    //        
    //        
    //        System.out.println(UUID.randomUUID().toString());

    //        int a = 1;
    //        a = doAdd(a);
    //        System.out.println(a);
    Pattern p = Pattern.compile("^\\d{1,9}(.\\d{1,2})?$");
    Matcher m = p.matcher("666666541.13");
    boolean b = m.matches();
    System.out.println(b);
    //          System.out.println(-2>>4);
    //        BigDecimal b = new BigDecimal(100.50);
    //        System.out.println(b.toString());
    // indexOf   ??
    //        String a = "?";
    //        
    //        String[] split = a.split("?");
    //        if(a.indexOf("?")>-1){
    //            System.out.println("111");
    //        }
    //        for(String s: split){
    //            System.out.println(s);
    //        }
    //        MapTestObject mto = new MapTestObject();
    //        mto.setOrderType(OrderType.TWO);
    //        
    //        String str = "\":\"";
    //        System.out.println(str);
    //        String a = ",";
    ////
    //        String[] splits = a.split(".");
    //        List<String> asList = Arrays.asList(splits);

    //        String last = "";
    //        String last = "";
    //        String last = "";
    //        if (!asList.isEmpty()) {
    //            if (asList.indexOf(last) > -1) {
    //                int indexOf = asList.indexOf(last);
    //                if (indexOf + 1 >= asList.size()) {
    //                    System.out.println("?");
    //                }else{
    //                    String next = asList.get(indexOf + 1);
    //                    if (OTHERStringUtils.isEmpty(next)) {
    //                        System.out.println("?");
    //                    } else {
    //                        System.out.println("?" + next);
    //                    }
    //                }
    //            } else {
    //                System.out.println("?");
    //            }
    //        } else {
    //            System.out.println("??");
    //        }

    //           System.out.println("?\",\""); 
    //           String a ="1123";
    //           a = StringUtils.substring(a, 0, a.length()-1);
    //           System.out.println("a="+a);
    //           
    int a = 0x12345678;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    DataOutputStream dos = new DataOutputStream(baos);
    dos.writeInt(a);
    System.out.println(Integer.toHexString(a));
    byte[] c = baos.toByteArray();
    for (int i = 0; i < 4; i++) {
        System.out.println(Integer.toHexString(c[i]));
    }
}

From source file:com.rslakra.java.TestUrlConnection.java

public static void main(String[] args) {
    String urlString = "https://devamatre.com/";
    HttpResponse httpResponse = HTTPHelper.executeGetRequest(urlString, null, true);
    System.out.println(httpResponse.getRequestHeaders());

    String formActionValue = extractFormActionValue(httpResponse.getDataBytes());
    System.out.println("\nformActionValue:\n" + formActionValue);

    String dataString = new String(httpResponse.getDataBytes());
    Pattern pattern = Pattern.compile("\"");
    Matcher matcher = pattern.matcher(dataString);
    if (matcher.matches()) {
        System.out.println("Matched\n");
        System.out.println(matcher.group(1));
    }/*w  ww . ja  v a  2  s  .c om*/

    System.out.println(StringEscapeUtils.unescapeHtml(urlString));
}

From source file:com.adobe.aem.demomachine.RegExp.java

public static void main(String[] args) throws IOException {

    String fileName = null;//from   www  .  j a v  a2s.  c o  m
    String regExp = null;
    String position = null;
    String value = "n/a";
    List<String> allMatches = new ArrayList<String>();

    // Command line options for this tool
    Options options = new Options();
    options.addOption("f", true, "Filename");
    options.addOption("r", true, "RegExp");
    options.addOption("p", true, "Position");
    CommandLineParser parser = new BasicParser();
    try {
        CommandLine cmd = parser.parse(options, args);

        if (cmd.hasOption("f")) {
            fileName = cmd.getOptionValue("f");
        }

        if (cmd.hasOption("f")) {
            regExp = cmd.getOptionValue("r");
        }

        if (cmd.hasOption("p")) {
            position = cmd.getOptionValue("p");
        }

        if (fileName == null || regExp == null || position == null) {
            System.out.println("Command line parameters: -f fileName -r regExp -p position");
            System.exit(-1);
        }

    } catch (ParseException ex) {

        logger.error(ex.getMessage());

    }

    String content = readFile(fileName, Charset.defaultCharset());

    if (content != null) {
        Matcher m = Pattern.compile(regExp).matcher(content);
        while (m.find()) {
            String group = m.group();
            int pos = group.indexOf(".zip");
            if (pos > 0) {
                group = group.substring(0, pos);
            }
            logger.debug("RegExp: " + m.group() + " found returning " + group);
            allMatches.add(group);
        }

        if (allMatches.size() > 0) {

            if (position.equals("first")) {
                value = allMatches.get(0);
            }

            if (position.equals("last")) {
                value = allMatches.get(allMatches.size() - 1);
            }
        }
    }

    System.out.println(value);

}