tags:

views:

115

answers:

5

The following should be matched:

AAA123
ABCDEFGH123
XXXX123

can i do: ".*123"?

+1  A: 

Use the pattern . to match any character once, .* to match any character zero or more times, .+ to match any character one or more times.

thr
+2  A: 

Yes, you can. That should work.

  • . = any char
  • \. = the actual dot character
  • .? = .{0,1} = match any char zero or one times
  • .* = .{0,} = match any char zero or more times
  • .+ = .{1,} = match any char one or more times
Delan Azabani
A: 

No, * will match zero-or-more characters. You should use + that matches one-or-more instead.

this expression might work better for you: [A-Z]+123

//Huusom

Huusom
+1  A: 

There are lots of sophisticated regex testing and development tools, but if you just want a simple test harness in Java, here's one for you to play with:

    String[] tests = {
        "AAA123",
        "ABCDEFGH123",
        "XXXX123",
        "XYZ123ABC",
        "123123",
        "X123",
        "123",
    };
    for (String test : tests) {
        System.out.println(test + " " +test.matches(".+123"));
    }

Now you can easily add new testcases and try new patterns. Have fun exploring regex.

See also

polygenelubricants
Upvote just for the regular-expressions.info link. Wonderful site for learning regular expressions and for reference.
Freiheit
A: 

Yes that will work, though note that . will not match newlines unless you pass the DOTALL flag when compiling the expression:

Pattern pattern = Pattern.compile(".*123", Pattern.DOTALL);
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
BlueRaja - Danny Pflughoeft