2

I try to generate my Pattern, to be able to set/add/edit it through JTextfield in UI for variant2 it works OK, but if I try to add more then one pattern (variant1) it stops to work.

Can you tell me what am I doing wrong?

Here is relevant part of code:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class TestSomeStaff {

String getPattern(String s) {
    String p = "";
    for (int i = 0; i < s.length(); i++) {
        if (Character.isLetter(s.charAt(i))) {
            p += "\\" + "w";
        } else if (Character.isDigit(s.charAt(i))) {
            p += "\\" + "d";
        } else {
            p += s.charAt(i);
        }
    }
    return p;
}

public static void main(String[] args) {
    String code1 = "11XXX08_XX000XX__XX11";
    String code2 = "11XXX08_XX000X__XX11";
    TestSomeStaff t = new TestSomeStaff();

    // String p="("+t.getPattern(code1) + ") | ("+t.getPattern(code2)+")";
    // //variant1
    String p = t.getPattern(code1); // variant 2
    System.out.println(t.getPattern(code1));
    Pattern pat = Pattern.compile(p);

    Matcher m = pat.matcher(code1);
    System.out.println("pattern:" + m.pattern());

    if (m.find()) {
        System.out.println(m.group());
    }
}
}

var1 output:

\d\d\w\w\w\d\d_\w\w\d\d\d\w\w__\w\w\d\d
pattern:(\d\d\w\w\w\d\d_\w\w\d\d\d\w\w__\w\w\d\d) | (\d\d\w\w\w\d\d_\w\w\d\d\d\w__\w\w\d\d)

var2 output:

\d\d\w\w\w\d\d_\w\w\d\d\d\w\w__\w\w\d\d
pattern:\d\d\w\w\w\d\d_\w\w\d\d\d\w\w__\w\w\d\d
11XXX08_XX000XX__XX11
1
  • 1
    Although it is not very clear what are you going to do, in order to match pattern you should remove spaces in variant 1: ")|(" Commented May 20, 2015 at 13:25

1 Answer 1

1

The spaces in the variant1 pattern are important. If you remove the space then the variant will work.

Sign up to request clarification or add additional context in comments.

1 Comment

Everything in a Regular Expression (Pattern) is means something.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.