How to find occurrences of a substring=“\r” in a string=“This is a \\rtest \n\r string” in java using Pattern and matchers
How to find occurrences of a substring=“\r” in a string=“This is a \\rtest \n\r string” in java using Pattern and matchers
How to find occurrences of a substring="r" in a string="This is a \rtest nr 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;
string="This is a \\rtest \n\r string"
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;
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 2 at 8:33
2 Answers
2
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 a \rtest \n\r string"
'\r'
'\'
''
'r'
This is also true for "This is a \\rtest \n\r string"
or any other not-even number of backslashes
"This is a \\rtest \n\r string"
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 \
.
\rtest
r
\
This r
has meaning in string library.
You can read this question : r diff n
r
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 .
\n\r
n
r
In shortly , change the string to get result correctly. if you write double backspace before the anything , you will escape after char.
Thanks for contributing an answer to Stack Overflow!
But avoid …
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
But avoid …
To learn more, see our tips on writing great answers.
Required, but never shown
Required, but never shown
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
you need to escape the backspace by duplicating it
– Sharon Ben Asher
Sep 2 at 7:51