2

I'm trying to get true in the following test. I have a string with the backslash, that for some reason doesn't recognized.

String s = "Good news\\ everyone!";
Boolean test = s.matches("(.*)news\\.");
System.out.println(test);

I've tried a lot of variants, but only one (.*)news(.*) works. But that actually means any characters after news, i need only with \.

How can i do that?

Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
HUESOS
  • 29
  • 2
  • 5
    With `"\\."`, you are trying to match a `.` symbol, not a ``\``. Use `s.matches(".*news\\\\.*")` – Wiktor Stribiżew Apr 18 '17 at 13:55
  • Possible duplicate of [What is the backslash character (\\‌)?](http://stackoverflow.com/questions/12091506/what-is-the-backslash-character) – Alex Apr 18 '17 at 13:59

5 Answers5

2

Group the elements at the end:(.*)news\\(.*)

Abhishek Kumar
  • 197
  • 2
  • 15
1

You can use this instead :

Boolean test = s.matches("(.*)news\\\\(.*)");
Youcef LAIDANI
  • 55,661
  • 15
  • 90
  • 140
0

Try something like:

Boolean test = s.matches(".*news\\\\.*");

Here .* means any number of characters followed by news, followed by double back slashes (escaped in a string) and then any number of characters after that (can be zero as well).

With your regex what it means is:

  • .* Any number of characters
  • news\\ - matches by "news\" (see one slash)
  • . followed by one character.

which doesn't satisfies for String in your program "Good news\ everyone!"

SMA
  • 36,381
  • 8
  • 49
  • 73
0

You are testing for an escaped occurrence of a literal dot: ".".

Refactor your pattern as follows (inferring the last part as you need it for a full match):

String s = "Good news\\ everyone!";
System.out.println(s.matches("(.*)news\\\\.*"));

Output

true

Explanation

  • The back-slash is used to escape characters and the back-slash itself in Java Strings
  • In Java Pattern representations, you need to double-escape your back-slashes for representing a literal back-slash ("\\\\"), as double-back-slashes are already used to represent special constructs (e.g. \\p{Punct}), or escape them (e.g. the literal dot \\.).
  • String.matches will attempt to match the whole String against your pattern, so you need the terminal part of the pattern I've added
Mena
  • 47,782
  • 11
  • 87
  • 106
0

you can try this :

String s = "Good news\\ everyone!";
Boolean test = s.matches("(.*)news\\\\(.*)");
System.out.println(test);
RAJNIK PATEL
  • 1,039
  • 1
  • 17
  • 30