Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java regular expression to match specific special characters

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.

like image 749
ccoder83 Avatar asked Feb 05 '26 01:02

ccoder83


1 Answers

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.

like image 163
M A Avatar answered Feb 06 '26 13:02

M A



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!