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, int flags) 

Source Link

Document

Compiles the given regular expression into a pattern with the given flags.

Usage

From source file:Main.java

public static void main(String[] argv) throws Exception {
    CharSequence inputStr = "a\rb";
    inputStr = "a\r\nb";
    inputStr = "a\nb";

    String patternStr = "^(.*)$";
    Pattern pattern = Pattern.compile(patternStr, Pattern.MULTILINE);
    Matcher matcher = pattern.matcher(inputStr);
    while (matcher.find()) {
        String lineWithTerminator = matcher.group(0);

        String lineWithoutTerminator = matcher.group(1);
    }//from   ww  w . j av  a  2  s  .co m
}

From source file:MainClass.java

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

    Pattern reCaseInsens = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
    Pattern reCaseSens = Pattern.compile(pattern);

    boolean found;
    Matcher m;//from   ww  w .  j av  a2s.  co  m
    m = reCaseInsens.matcher(input); // will match any case
    found = m.lookingAt(); // will match any case
    System.out.println("IGNORE_CASE match " + found);

    m = reCaseSens.matcher(input); // Get matcher w/o case-insens flag
    found = m.lookingAt(); // will match case-sensitively
    System.out.println("MATCH_NORMAL match was " + found);

}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    CharSequence inputStr = "a\r\rb"; // Mac
    //inputStr = "a\r\n\r\nb"; // Windows
    //inputStr = "a\n\nb"; // Unix

    String patternStr = "(?<=(\r\n|\r|\n))([ \\t]*$)+";

    String[] paras = Pattern.compile(patternStr, Pattern.MULTILINE).split(inputStr);

    for (int i = 0; i < paras.length; i++) {
        String paragraph = paras[i];
    }//from www.  jav a  2 s  .  c  om
}

From source file:Main.java

public static void main(String[] argv) throws Exception {

    CharSequence inputStr = "a\r\rb"; // Mac
    //inputStr = "a\r\n\r\nb"; // Windows
    //inputStr = "a\n\nb"; // Unix

    String patternStr = "(^.*\\S+.*$)+";
    Pattern pattern = Pattern.compile(patternStr, Pattern.MULTILINE);
    Matcher matcher = pattern.matcher(inputStr);

    while (matcher.find()) {
        String paragraph = matcher.group();
    }//w w w  . j a v  a2s . c o  m
}

From source file:MainClass.java

public static void main(String[] args) {
    String pattStr = "\u00e9gal"; // gal
    String[] input = { "\u00e9gal", // gal - this one had better match :-)
            "e\u0301gal", // e + "Combining acute accent"
            "e\u02cagal", // e + "modifier letter acute accent"
            "e'gal", // e + single quote
            "e\u00b4gal", // e + Latin-1 "acute"
    };/*from   ww  w. java  2s . c om*/
    Pattern pattern = Pattern.compile(pattStr, Pattern.CANON_EQ);
    for (int i = 0; i < input.length; i++) {
        if (pattern.matcher(input[i]).matches()) {
            System.out.println(pattStr + " matches input " + input[i]);
        } else {
            System.out.println(pattStr + " does not match input " + input[i]);
        }
    }
}

From source file:TheReplacements.java

public static void main(String[] args) throws Exception {
    String s = TextFile.read("TheReplacements.java");
    // Match the specially-commented block of text above:
    Matcher mInput = Pattern.compile("/\\*!(.*)!\\*/", Pattern.DOTALL).matcher(s);
    if (mInput.find())
        s = mInput.group(1); // Captured by parentheses
    // Replace two or more spaces with a single space:
    s = s.replaceAll(" {2,}", " ");
    // Replace one or more spaces at the beginning of each
    // line with no spaces. Must enable MULTILINE mode:
    s = s.replaceAll("(?m)^ +", "");
    System.out.println(s);/* www. j  a  v a  2  s.  c  o  m*/
    s = s.replaceFirst("[aeiou]", "(VOWEL1)");
    StringBuffer sbuf = new StringBuffer();
    Pattern p = Pattern.compile("[aeiou]");
    Matcher m = p.matcher(s);
    // Process the find information as you
    // perform the replacements:
    while (m.find())
        m.appendReplacement(sbuf, m.group().toUpperCase());
    // Put in the remainder of the text:
    m.appendTail(sbuf);
    System.out.println(sbuf);

}

From source file:WordCount.java

public static void main(String args[]) throws Exception {
    String filename = "WordCount.java";

    // Map File from filename to byte buffer
    FileInputStream input = new FileInputStream(filename);
    FileChannel channel = input.getChannel();
    int fileLength = (int) channel.size();
    MappedByteBuffer buffer = channel.map(FileChannel.MapMode.READ_ONLY, 0, fileLength);

    // Convert to character buffer
    Charset charset = Charset.forName("ISO-8859-1");
    CharsetDecoder decoder = charset.newDecoder();
    CharBuffer charBuffer = decoder.decode(buffer);

    // Create line pattern
    Pattern linePattern = Pattern.compile(".*$", Pattern.MULTILINE);

    // Create word pattern
    Pattern wordBreakPattern = Pattern.compile("[\\p{Punct}\\s}]");

    // Match line pattern to buffer
    Matcher lineMatcher = linePattern.matcher(charBuffer);

    Map map = new TreeMap();
    Integer ONE = new Integer(1);

    // For each line
    while (lineMatcher.find()) {
        // Get line
        CharSequence line = lineMatcher.group();

        // Get array of words on line
        String words[] = wordBreakPattern.split(line);

        // For each word
        for (int i = 0, n = words.length; i < n; i++) {
            if (words[i].length() > 0) {
                Integer frequency = (Integer) map.get(words[i]);
                if (frequency == null) {
                    frequency = ONE;/*from  w w  w  .  j  a v a2s .com*/
                } else {
                    int value = frequency.intValue();
                    frequency = new Integer(value + 1);
                }
                map.put(words[i], frequency);
            }
        }
    }
    System.out.println(map);
}

From source file:HrefMatch.java

public static void main(String[] args) {
    try {//from ww w  .  j  a va2s  . c  o  m
        // get URL string from command line or use default
        String urlString;
        if (args.length > 0)
            urlString = args[0];
        else
            urlString = "http://java.sun.com";

        // open reader for URL
        InputStreamReader in = new InputStreamReader(new URL(urlString).openStream());

        // read contents into string builder
        StringBuilder input = new StringBuilder();
        int ch;
        while ((ch = in.read()) != -1)
            input.append((char) ch);

        // search for all occurrences of pattern
        String patternString = "<a\\s+href\\s*=\\s*(\"[^\"]*\"|[^\\s>]*)\\s*>";
        Pattern pattern = Pattern.compile(patternString, Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(input);

        while (matcher.find()) {
            int start = matcher.start();
            int end = matcher.end();
            String match = input.substring(start, end);
            System.out.println(match);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } catch (PatternSyntaxException e) {
        e.printStackTrace();
    }
}

From source file:com.lehman.ic9.ic9Main.java

/**
 * Program entry point./*w w  w .  ja  va  2s.  c o m*/
 * @param args is an array of strings from the OS.
 */
public static void main(String[] args) {

    try {
        if (args.length >= 1) {
            if (parseScriptArgs(args)) {
                if (file.exists(script)) {
                    // Load dependent jars in assemblyPath/lib-depends directory.
                    jarLoader.getInstance().loadJarsInPathRecursively(sys.getAssemblyPath() + "lib-depends",
                            debug);

                    // Load dependent jars in assemblyPath/lib directory if any.
                    jarLoader.getInstance().loadJarsInPathRecursively(sys.getAssemblyPath() + "lib", debug);

                    // Create the Ic9 engine and eval the script.
                    String[] engArgs = { "-scripting" };
                    ic9engine eng = new ic9engine(engArgs);
                    eng.setMainArgs(script, scriptArgs);

                    // Remove shebang if it exists.
                    String contents = Pattern.compile("^#!/.*?$", Pattern.MULTILINE).matcher(file.read(script))
                            .replaceAll("");
                    eng.eval(script, contents);

                    // If -t flag, attempt to call test() function.
                    if (runTest) {
                        eng.runTest();
                    }
                } else {
                    System.err.println("File '" + script + "' couldn't be found.");
                }
            }
        } else {
            runInteractive();
        }
    } catch (ScriptException e) {
        e.printStackTrace();
    } catch (ic9exception e) {
        e.printStackTrace();
    } catch (NoSuchMethodException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:CanonEqDemo.java

public static void main(String[] args) {
    String pattStr = "\u00e9gal"; // Zgal
    String[] input = { "\u00e9gal", // Zgal - this one had better match :-)
            "e\u0301gal", // e + "Combining acute accent"
            "e\u02cagal", // e + "modifier letter acute accent"
            "e'gal", // e + single quote
            "e\u00b4gal", // e + Latin-1 "acute"
    };/*w ww.ja  va 2  s. co m*/
    Pattern pattern = Pattern.compile(pattStr, Pattern.CANON_EQ);
    for (int i = 0; i < input.length; i++) {
        if (pattern.matcher(input[i]).matches()) {
            System.out.println(pattStr + " matches input " + input[i]);
        } else {
            System.out.println(pattStr + " does not match input " + input[i]);
        }
    }
}