-2

How to find occurrences of a substring="\r" in a string="This is a \\rtest \n\r string" in java using Pattern and matchers.

When I use

Pattern p4=Pattern.compile("\\r",Pattern.LITERAL);

Even then this is not working

It worked well when I have string="This is a \\rtest \\n\\r string".It have me correct count i.e..2

But for string="This is a \\\\\rtest \\\n\\\r string". It gave me incorrect count =1;

function to be called:

static int countMatches(Pattern pattern, String string)
{

    Matcher matcher=pattern.matcher(string);
    int count=0;
    int pos=0;
    while(matcher.find(pos))

    {
        count++;
        pos=matcher.start()+1;

    }

    return count;

}
Prashant Pimpale
  • 10,349
  • 9
  • 44
  • 84
  • you need to escape the backspace by duplicating it – Sharon Ben Asher Sep 02 '18 at 07:51
  • Use [edit] option and post your string using code formatting (`{}` icon on editors options). Otherwise we wouldn't know how many ``\`` you really have in your string and what exactly you want to find. – Pshemo Sep 02 '18 at 08:33

2 Answers2

0

The problem is that the String "This is a \\\rtest \\n\\r string" really does not contain two occurences of '\\r'. the first occurence is interprated by the compiler as the two characters '\\' (which is a single backsapce '\') and '\r' (which is something unprintable)

This is also true for "This is a \\\\\rtest \\n\\r string" or any other not-even number of backslashes

Sharon Ben Asher
  • 13,849
  • 5
  • 33
  • 47
0

In string you can use \\ if u want to escape character. So in your string

String string="This is a \\\rtest \\n\\r string";

In this string \\\rtest part is escaping the \r part with double backslash \\.

This \r has meaning in string library. You can read this question : \r diff \n

So in your example \r could not see in your variable string. If you change the string with this you can get result as 2 ;

String string="This is a \\\rtest \\n\\r string";

in your string second part as \\n\\r there is saving the \n with \ and \r with \.

In shortly , change the string to get result correctly. if you write double backspace before the anything , you will escape after char.

drowny
  • 2,067
  • 11
  • 19