Page 1 of 1

About Question com.enthuware.ocpjp.v7.2.1182

Posted: Wed Oct 01, 2014 6:46 am
by sasha32003
What will the following code print?
       

Code: Select all

String str = "she sells sea shells";
        String rex = "\\Ss\\S";
        String replace = "X";
        Pattern p = Pattern.compile(rex);
        Matcher m = p.matcher(str);
        String val = m.replaceAll(replace);
        System.out.println(val);
The right answer is: she sells sea shells
Explanation: \\S implies any non-white space character. Therefore, \\Ss\\S matches any s that is surrounded by a non white space character on both sides. There is no such s in the given input and so there is no change.

Ok, explanation perfectly clear, tested that piece of code, got the output as expected she sells sea shells. But isn't there two s so rounded by NON white space? she sells sea shells. They both so rounded by beginning&end of string and characters. I mean there is no white space at beginning and end of that string???

Could anyone please clear this?
Thanks in advance.

Re: About Question com.enthuware.ocpjp.v7.2.1182

Posted: Wed Oct 01, 2014 10:13 am
by admin
Beginning and end of a String do not match \S because they are not non-white space.

HTH,
Paul.

Re: About Question com.enthuware.ocpjp.v7.2.1182

Posted: Wed Oct 01, 2014 11:00 am
by sasha32003
admin wrote:Beginning and end of a String do not match \S because they are not non-white space.

HTH,
Paul.

Thank you Paul.

Re: About Question com.enthuware.ocpjp.v7.2.1182

Posted: Fri Jan 29, 2016 4:18 pm
by krohani
Isn't beginning and end of string consider a word boundary (\b) and I thought a word boundary (\b) was considered a non-white space? What am I not understanding here?

Re: About Question com.enthuware.ocpjp.v7.2.1182

Posted: Fri Jan 29, 2016 9:07 pm
by admin
\b is indeed for word boundary. But the search expression is \\Ss\\S. It is not looking for word boundary. So why do you expect it to match word boundary?