Example usage for java.util.regex Matcher lookingAt

List of usage examples for java.util.regex Matcher lookingAt

Introduction

In this page you can find the example usage for java.util.regex Matcher lookingAt.

Prototype

public boolean lookingAt() 

Source Link

Document

Attempts to match the input sequence, starting at the beginning of the region, against the 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);//w w w.  j a  v  a 2s . com
    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: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);/*w ww.  j a v  a  2 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;

        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:StartEnd.java

public static void main(String[] args) {
    String[] input = new String[] { "Java has regular expressions in 1.4",
            "regular expressions now expressing in Java", "Java represses oracular expressions" };
    Pattern p1 = Pattern.compile("re\\w*"), p2 = Pattern.compile("Java.*");
    for (int i = 0; i < input.length; i++) {
        System.out.println("input " + i + ": " + input[i]);
        Matcher m1 = p1.matcher(input[i]), m2 = p2.matcher(input[i]);
        while (m1.find())
            System.out.println("m1.find() '" + m1.group() + "' start = " + m1.start() + " end = " + m1.end());
        while (m2.find())
            System.out.println("m2.find() '" + m2.group() + "' start = " + m2.start() + " end = " + m2.end());
        if (m1.lookingAt()) // No reset() necessary
            System.out.println("m1.lookingAt() start = " + m1.start() + " end = " + m1.end());
        if (m2.lookingAt())
            System.out.println("m2.lookingAt() start = " + m2.start() + " end = " + m2.end());
        if (m1.matches()) // No reset() necessary
            System.out.println("m1.matches() start = " + m1.start() + " end = " + m1.end());
        if (m2.matches())
            System.out.println("m2.matches() start = " + m2.start() + " end = " + m2.end());
    }//  ww  w. j a  v a2  s .  c  o  m
}

From source file:gov.nih.nci.caarray.web.util.UserComparator.java

/**
 * Extracts last and first name from a string like <code>&lt;a href="..."&gt;last, first&lt;/a&gt;</code>.
 * @param s the html to extrat names from
 * @return UPPER(last), UPPER(first)/*from  w  w w.ja  va 2  s  .c  o m*/
 */
public static String[] getNames(String s) {
    Pattern p = Pattern.compile("[^>]*>\\s*(.*),\\s*(.*)<[^<]*");
    Matcher m = p.matcher(s.toUpperCase(Locale.US));
    m.lookingAt();
    return new String[] { m.group(1).trim(), m.group(2).trim() };
}

From source file:ar.com.zauber.commons.spring.web.CommandURLParameterGenerator.java

/**
 * @see #getURLParameter(Class, Set)//from   w  w w .  jav a  2  s  .  co  m
 */
public static String getURLParameter(final Class<?> cmdClass, final Map<Class<?>, Object> values) {
    final StringBuilder sb = new StringBuilder("?");
    final Pattern getter = Pattern.compile("^get(.*)$");
    boolean first = true;

    // look for getters
    for (final Method method : cmdClass.getMethods()) {
        final Matcher matcher = getter.matcher(method.getName());
        if (matcher.lookingAt() && matcher.groupCount() == 1 && method.getParameterTypes().length == 0
                && values.containsKey(method.getReturnType())) {
            try {
                cmdClass.getMethod("set" + matcher.group(1), new Class[] { method.getReturnType() });
                if (!first) {
                    sb.append("&");
                } else {
                    first = false;
                }

                sb.append(URLEncoder.encode(matcher.group(1).toLowerCase(), CHARSET));
                sb.append("=");
                sb.append(URLEncoder.encode(values.get(method.getReturnType()).toString(), CHARSET));
            } catch (Exception e) {
                // skip
            }
        }
    }

    return sb.toString();
}

From source file:com.manydesigns.elements.util.Util.java

public static String getAbsoluteUrl(HttpServletRequest req, String url) {
    StringBuilder sb = new StringBuilder();

    Matcher matcher = pattern.matcher(url);
    if (matcher.lookingAt()) {
        return url;
    }// w  w w.  j  ava 2  s .com

    if (!"/".equals(req.getContextPath())) {
        sb.append(req.getContextPath());
    }

    if (!url.startsWith("/")) {
        sb.append("/");
    }

    sb.append(url);

    return sb.toString();
}

From source file:examples.mail.IMAPExportMbox.java

private static boolean startsWith(String input, Pattern pat) {
    Matcher m = pat.matcher(input);
    return m.lookingAt();
}

From source file:examples.mail.IMAPExportMbox.java

private static String matches(String input, Pattern pat, int index) {
    Matcher m = pat.matcher(input);
    if (m.lookingAt()) {
        return m.group(index);
    }//  w ww  . ja va  2 s  .  co  m
    return null;
}

From source file:com.perl5.lang.perl.lexer.RegexBlock.java

/**
 * Parses guaranteed opened regex block/*  ww  w . j  av a  2  s.c  om*/
 *
 * @param buffer      Input characters stream
 * @param startOffset Start parsing offset
 * @param bufferEnd   Buffer last offset
 * @param openingChar Opener character
 * @return Parsed regex block or null if failed
 */
public static RegexBlock parseBlock(CharSequence buffer, int startOffset, int bufferEnd, char openingChar,
        boolean isSecondBlock) {
    char closingChar = getQuoteCloseChar(openingChar);

    boolean isEscaped = false;
    boolean isCharGroup = false;
    boolean isQuotesDiffers = closingChar != openingChar;

    int braceLevel = 0;
    int parenLevel = 0;
    int delimiterLevel = 0;

    RegexBlock newBlock = null;
    int currentOffset = startOffset;

    while (true) {
        if (currentOffset >= bufferEnd) {
            break;
        }

        char currentChar = buffer.charAt(currentOffset);

        if (delimiterLevel == 0 && braceLevel == 0 && !isCharGroup && !isEscaped && parenLevel == 0
                && closingChar == currentChar) {
            newBlock = new RegexBlock(buffer, startOffset, currentOffset + 1, openingChar, closingChar);
            break;
        }

        if (!isSecondBlock) {
            if (!isEscaped && !isCharGroup && currentChar == '[') {
                Matcher m = POSIX_CHAR_CLASS_PATTERN.matcher(buffer.subSequence(currentOffset, bufferEnd));
                if (m.lookingAt()) {
                    currentOffset += m.toMatchResult().group(0).length();
                    continue;
                } else {
                    isCharGroup = true;
                }
            } else if (!isEscaped && isCharGroup && currentChar == ']') {
                isCharGroup = false;
            }

            // @todo this is buggy, sometimes bare is allowed. See example from `redo` doc
            //            if (!isEscaped && !isCharGroup && currentChar == '{')
            //               braceLevel++;
            //            else if (!isEscaped && !isCharGroup && braceLevel > 0 && currentChar == '}')
            //               braceLevel--;
            //
            //            if (!isEscaped && !isCharGroup && currentChar == '(')
            //               parenLevel++;
            //            else if (!isEscaped && !isCharGroup && parenLevel > 0 && currentChar == ')')
            //               parenLevel--;
        }

        if (!isEscaped && isQuotesDiffers && !isCharGroup) {
            if (currentChar == openingChar) {
                delimiterLevel++;
            } else if (currentChar == closingChar && delimiterLevel > 0) {
                delimiterLevel--;
            }
        }

        isEscaped = !isEscaped && closingChar != '\\' && currentChar == '\\';

        currentOffset++;
    }
    return newBlock;
}

From source file:com.squarespace.template.TestCaseParser.java

/**
 * Parses a simplistic format of sections annotated by keys:
 *
 *   :<KEY-1>//from ww  w.  j  av  a2 s  .co  m
 *   [ one or more lines ]
 *
 *   :<KEY-n>
 *   [ one or more lines ]
 */
public static Map<String, String> parseSections(String source) {
    Matcher matcher = RE_SECTION.matcher("");
    String[] lines = RE_LINES.split(source);

    Map<String, String> sections = new HashMap<>();
    String key = null;
    StringBuilder buf = new StringBuilder();

    int size = lines.length;
    for (int i = 0; i < size; i++) {
        matcher.reset(lines[i]);
        if (matcher.lookingAt()) {
            if (key != null) {
                sections.put(key, buf.toString());
                buf.setLength(0);
            }
            key = matcher.group(1);

        } else {
            buf.append('\n');
            buf.append(lines[i]);
        }
    }

    if (!sections.containsKey(key)) {
        sections.put(key, buf.toString());
    }
    return sections;
}