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:org.eclipse.swt.snippets.Snippet196.java

public static void main(String[] args) {

    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setText("Snippet 196");
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    Font font = new Font(display, "Courier New", 10, SWT.NONE); //$NON-NLS-1$
    text.setFont(font);/*  ww  w . ja v a2  s. c  o m*/
    text.setText(template);
    text.addListener(SWT.Verify, new Listener() {
        //create the pattern for verification
        Pattern pattern = Pattern.compile(REGEX);
        //ignore event when caused by inserting text inside event handler
        boolean ignore;

        @Override
        public void handleEvent(Event e) {
            if (ignore)
                return;
            e.doit = false;
            if (e.start > 13 || e.end > 14)
                return;
            StringBuilder buffer = new StringBuilder(e.text);

            //handle backspace
            if (e.character == '\b') {
                for (int i = e.start; i < e.end; i++) {
                    // skip over separators
                    switch (i) {
                    case 0:
                        if (e.start + 1 == e.end) {
                            return;
                        } else {
                            buffer.append('(');
                        }
                        break;
                    case 4:
                        if (e.start + 1 == e.end) {
                            buffer.append(new char[] { '#', ')' });
                            e.start--;
                        } else {
                            buffer.append(')');
                        }
                        break;
                    case 8:
                        if (e.start + 1 == e.end) {
                            buffer.append(new char[] { '#', '-' });
                            e.start--;
                        } else {
                            buffer.append('-');
                        }
                        break;
                    default:
                        buffer.append('#');
                    }
                }
                text.setSelection(e.start, e.start + buffer.length());
                ignore = true;
                text.insert(buffer.toString());
                ignore = false;
                // move cursor backwards over separators
                if (e.start == 5 || e.start == 9)
                    e.start--;
                text.setSelection(e.start, e.start);
                return;
            }

            StringBuilder newText = new StringBuilder(defaultText);
            char[] chars = e.text.toCharArray();
            int index = e.start - 1;
            for (int i = 0; i < e.text.length(); i++) {
                index++;
                switch (index) {
                case 0:
                    if (chars[i] == '(')
                        continue;
                    index++;
                    break;
                case 4:
                    if (chars[i] == ')')
                        continue;
                    index++;
                    break;
                case 8:
                    if (chars[i] == '-')
                        continue;
                    index++;
                    break;
                }
                if (index >= newText.length())
                    return;
                newText.setCharAt(index, chars[i]);
            }
            // if text is selected, do not paste beyond range of selection
            if (e.start < e.end && index + 1 != e.end)
                return;
            Matcher matcher = pattern.matcher(newText);
            if (matcher.lookingAt()) {
                text.setSelection(e.start, index + 1);
                ignore = true;
                text.insert(newText.substring(e.start, index + 1));
                ignore = false;
            }
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    font.dispose();
    display.dispose();
}

From source file:Split1.java

public static void main(String[] args) {
    String[] x = Pattern.compile("ian").split("the darwinian devonian explodian chicken");
    for (int i = 0; i < x.length; i++) {
        System.out.println(i + " \"" + x[i] + "\"");
    }/*from  w  w  w. j  a va 2 s .  c om*/
}

From source file:com.github.xbn.examples.regexutil.non_xbn.UserInputNumInRangeWRegex.java

public static final void main(String[] ignored) {

    int num = -1;
    boolean isNum = false;

    int iRangeMax = 2055;

    //"": Dummy string, to reuse matcher
    Matcher mtchrNumNegThrPos = Pattern.compile("-?\\b(20(5[0-5]|[0-4][0-9])|1?[0-9]{1,3})\\b").matcher("");

    do {//from   www  .j  a v  a2 s  .  c  om
        System.out.print("Enter a number between -" + iRangeMax + " and " + iRangeMax + ": ");
        String strInput = (new Scanner(System.in)).next();
        if (!NumberUtils.isNumber(strInput)) {
            System.out.println("Not a number. Try again.");
        } else if (!mtchrNumNegThrPos.reset(strInput).matches()) {
            System.out.println("Not in range. Try again.");
        } else {
            //Safe to convert
            num = Integer.parseInt(strInput);
            isNum = true;
        }
    } while (!isNum);

    System.out.println("Number: " + num);
}

From source file:MatcherTest.java

public static void main(String[] argv) {
    Pattern p = Pattern.compile(REGEX);
    Matcher m = p.matcher(INPUT); // get a matcher object
    int count = 0;
    while (m.find()) {
        count++;/*from   www.j  av  a  2  s  . c o  m*/
        System.out.println("Match number " + count);
        System.out.println("start(): " + m.start());
        System.out.println("end(): " + m.end());
    }
}

From source file:RegexTest.java

public static void main(String[] args) {
    Pattern p = Pattern.compile(REGEX);
    Matcher m = p.matcher(INPUT); // get a matcher object
    StringBuffer sb = new StringBuffer();
    while (m.find()) {
        m.appendReplacement(sb, REPLACE);
    }/*from  www .  ja  v a2  s.  co  m*/
    m.appendTail(sb);
    System.out.println(sb.toString());
}

From source file:ReaderIter.java

public static void main(String[] args) throws IOException {
    // The RE pattern
    Pattern patt = Pattern.compile("[A-Za-z][a-z]+");
    // A FileReader (see the I/O chapter)
    BufferedReader r = new BufferedReader(new FileReader("ReaderIter.java"));

    // For each line of input, try matching in it.
    String line;//ww  w .j a v  a 2 s. c  o m
    while ((line = r.readLine()) != null) {
        // For each match in the line, extract and print it.
        Matcher m = patt.matcher(line);
        while (m.find()) {
            // Simplest method:
            // System.out.println(m.group(0));

            // Get the starting position of the text
            int start = m.start(0);
            // Get ending position
            int end = m.end(0);
            // Print whatever matched.
            // Use CharacterIterator.substring(offset, end);
            System.out.println(line.substring(start, end));
        }
    }
}

From source file:TextVerifyInputRegularExpression.java

public static void main(String[] args) {

    Display display = new Display();
    Shell shell = new Shell(display);
    shell.setLayout(new GridLayout());
    final Text text = new Text(shell, SWT.BORDER);
    Font font = new Font(display, "Courier New", 10, SWT.NONE); //$NON-NLS-1$
    text.setFont(font);/*from  w w  w .ja  v  a 2  s.co  m*/
    text.setText(template);
    text.addListener(SWT.Verify, new Listener() {
        // create the pattern for verification
        Pattern pattern = Pattern.compile(REGEX);

        // ignore event when caused by inserting text inside event handler
        boolean ignore;

        public void handleEvent(Event e) {
            if (ignore)
                return;
            e.doit = false;
            if (e.start > 13 || e.end > 14)
                return;
            StringBuffer buffer = new StringBuffer(e.text);

            // handle backspace
            if (e.character == '\b') {
                for (int i = e.start; i < e.end; i++) {
                    // skip over separators
                    switch (i) {
                    case 0:
                        if (e.start + 1 == e.end) {
                            return;
                        } else {
                            buffer.append('(');
                        }
                        break;
                    case 4:
                        if (e.start + 1 == e.end) {
                            buffer.append(new char[] { '#', ')' });
                            e.start--;
                        } else {
                            buffer.append(')');
                        }
                        break;
                    case 8:
                        if (e.start + 1 == e.end) {
                            buffer.append(new char[] { '#', '-' });
                            e.start--;
                        } else {
                            buffer.append('-');
                        }
                        break;
                    default:
                        buffer.append('#');
                    }
                }
                text.setSelection(e.start, e.start + buffer.length());
                ignore = true;
                text.insert(buffer.toString());
                ignore = false;
                // move cursor backwards over separators
                if (e.start == 5 || e.start == 9)
                    e.start--;
                text.setSelection(e.start, e.start);
                return;
            }

            StringBuffer newText = new StringBuffer(defaultText);
            char[] chars = e.text.toCharArray();
            int index = e.start - 1;
            for (int i = 0; i < e.text.length(); i++) {
                index++;
                switch (index) {
                case 0:
                    if (chars[i] == '(')
                        continue;
                    index++;
                    break;
                case 4:
                    if (chars[i] == ')')
                        continue;
                    index++;
                    break;
                case 8:
                    if (chars[i] == '-')
                        continue;
                    index++;
                    break;
                }
                if (index >= newText.length())
                    return;
                newText.setCharAt(index, chars[i]);
            }
            // if text is selected, do not paste beyond range of selection
            if (e.start < e.end && index + 1 != e.end)
                return;
            Matcher matcher = pattern.matcher(newText);
            if (matcher.lookingAt()) {
                text.setSelection(e.start, index + 1);
                ignore = true;
                text.insert(newText.substring(e.start, index + 1));
                ignore = false;
            }
        }
    });

    shell.pack();
    shell.open();
    while (!shell.isDisposed()) {
        if (!display.readAndDispatch())
            display.sleep();
    }
    font.dispose();
    display.dispose();
}

From source file:REmatch.java

public static void main(String[] argv) {

    String patt = "Q[^u]\\d+\\.";
    Pattern r = Pattern.compile(patt);
    String line = "Order QT300. Now!";
    Matcher m = r.matcher(line);/*  www.j  av a2 s. c o m*/
    if (m.find()) {
        System.out.println(patt + " matches \"" + m.group(0) + "\" in \"" + line + "\"");
    } else {
        System.out.println("NO MATCH");
    }
}

From source file:com.github.xbn.examples.regexutil.non_xbn.MatchEachWordInEveryLine.java

public static final void main(String[] as_1RqdTxtFilePath) {
    Iterator<String> lineItr = null;
    try {/*from  w  w w .j  a  va2s .  co m*/
        lineItr = FileUtils.lineIterator(new File(as_1RqdTxtFilePath[0])); //Throws npx if null
    } catch (IOException iox) {
        throw new RuntimeException("Attempting to open \"" + as_1RqdTxtFilePath[0] + "\"", iox);
    } catch (RuntimeException rx) {
        throw new RuntimeException("One required parameter: The path to the text file.", rx);
    }

    //Dummy search string (""), so it can be reused (reset)
    Matcher mWord = Pattern.compile("\\b\\w+\\b").matcher("");
    while (lineItr.hasNext()) {
        String sLine = lineItr.next();
        mWord.reset(sLine);
        while (mWord.find()) {
            System.out.println(mWord.group());
        }
    }

}

From source file:RE_QnotU_Args.java

public static void main(String[] argv) {
    String patt = "^Q[^u]\\d+\\.";
    Pattern r = Pattern.compile(patt);
    Matcher m = r.matcher("RE_QnotU_Args");
    boolean found = m.lookingAt();
    System.out.println(patt + (found ? " matches " : " doesn't match ") + "RE_QnotU_Args");

}