0

I'm trying pattern matching expression for a below string. But it doesn't work. could you anybody help me on this ? Only Alphanumeric and underscore allowed inside,Both side $ sign will be there. Ex strings: Test_1,23_test_2,test3.

        String text = "$test_1$";
    Pattern p = Pattern.compile("$([A-Za-z0-9_])$");


    Matcher m = p.matcher(text);
    m.matches();
    if (m.find()) {
      System.out.println("Matched: " + m.group(1));
    } else {
      System.out.println("No match.");
    }
Alan Moore
  • 73,866
  • 12
  • 100
  • 156
Selva
  • 179
  • 1
  • 3
  • 13

3 Answers3

3

Your regex should be:

Pattern p = Pattern.compile("(\\$[A-Za-z0-9_]*\\$)");
Szymon
  • 42,577
  • 16
  • 96
  • 114
1

You could simply do...

s.matches("\\$[a-zA-Z0-9_]*\\$")
TheLostMind
  • 35,966
  • 12
  • 68
  • 104
0

$ is a regex meta character and should be escaped, try this

    Pattern p = Pattern.compile("\\$([A-Za-z0-9_]+)\\$");
Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275