3

I have input strings containing these special characters in any order: * . and \n

I want to make sure that there are no other characters in the string and \n should always be together and not something like *.*..\..n, so I want to match the string exactly in Java using a regular expression.

I tried using a regular expression to determine if an input string matches the pattern as below:

    String input = "*.*.*.\n..";
    System.out.println(input.matches("[\\\\.*\\n]"));

However, the output is false.

I tried using the double escape characters, in order to deal with Java's use of escape characters, but the result isn't as expected.

ccoder83
  • 504
  • 6
  • 15
  • 1
    Sorry, do you mean your input should only contain literal `*`, `.` and *newline* symbols? Or `*`, `.`, ``\`` and `n`? If you have newlines, then you need something like `input.matches("[.*\n]*")` or `input.matches("[.*\n]+")` (if at least 1 symbol is required in the input). – Wiktor Stribiżew Feb 16 '17 at 14:00
  • @Wiktor Perfect, that worked for me, thanks! Yes, I meant the *newline* symbols. The `input.matches("[.*\n]*")` is what I wanted, as I don't need atleast 1 symbol. For completeness, in Java, it would be `input.matches("[.*\\n]*")`. – ccoder83 Feb 16 '17 at 14:51
  • 1
    In Java, it is enough to write `input.matches("[.*\n]*")`. Anyway, it has already been posted – Wiktor Stribiżew Feb 16 '17 at 14:52

3 Answers3

1

You just need to add the * quantifier to match more than one character. Also, there is no need to escape the literal dot:

String input = "*.*.*.\n..";
System.out.println(input.matches("[.*\\n]*"));

[.*\\n] matches a ., or a * or the literal newline character \n.

M A
  • 71,713
  • 13
  • 134
  • 174
0

Turns out the matches method on String does not do what you expect it to do Regex doesn't work in String.matches()

You need to you Java's Pattern and Matcher classes.

Community
  • 1
  • 1
IgnitiousNites
  • 155
  • 1
  • 1
  • 7
0

\s we have to use for a whitespace character: [ \t\n\x0B\f\r]

String stringToSearch = "...\n..\n..\n.*.*.*.*...*.*";
System.out.println(stringToSearch.matches("[.*\\s]*"));
Avaneesh
  • 162
  • 5