开发者

Double "Pipes" in title

At my job today, I was made aware of a little error in our pages' titles. Our site is built using .jsp pages and for the titles of our product pages we use

In our admi开发者_StackOverflow中文版n (where we can set up the titles for each of the products), we would normally add in * anyone ever run into this issue before, and if so, does anyone know of a way to fix the double pipes issue I have encountered?


Problem is that the method replaceAll has as the first argument regular expression. The "|" is reserved symbol in regular expressions and you must escape it if you want use it as a string literal. You can create workaround, for example this way.

String[] words = str.split(" ");
for (int i = 0; i < words.length; i++) {
  if (words[i].length() > 0) {
    if (!(words[i].substring(0, 1).equals("|"))) {
      sb.append(words[i].replaceFirst(words[i].substring(0, 1), words[i].substring(0, 1).toUpperCase()) + " ");
    } else {
      sb.append(words[i] + " ");
    }
  }
}


Try using the html escape code for the pipe character &brvbar;.

Your title would be:

"Monkey Thank You &brvbar; Monkey Thank You Cards"


I think the issue is in the fact that replaceFirst() takes a regex as parameter and a replacement string. Because you push in the first character as is for the regex parameter, what happens with the vertical bar is (omitting adding to the StringBuffer) equivalent to:

String addedToBuffer = "|".replaceFirst("|", "|".toUpperCase());

What happens then, is that we have a regex which matches the empty string or the empty string. Well, any string matches the empty string regex. So the match gets replaced by "|" (to upper case). So "|".replaceFirst("|", "|".toUpperCase()) expands to "||". So the append() call is given the parameter of "|| ".

You can fix your algorithm in two ways:

  1. Fix the regex automatically, use literal notation in between \Q and \E. So your regex to pass to replaceFirst() becomes something like "\\Q"+ literal + "\\E".
  2. Realise that you do not need regexes in the first place. Instead use two append() operations. One to append() the case converted first character of the item to add, the other to append the rest. This looks like this:

    for(String s: items) { if(s.equals("")) { sb.append(" "); } else { sb.append(Character.toUpperCase(s.charAt(0))); if(s.length() > 1) { sb.append(s.substring(1)); } sb.append(" "); } }

The second approach is probably much easier to follow as well.

PS: For some reason the StackOverflow editor is vehemently disagreeing with code blocks in lists. If someone happens to know how to fix the munged formatting... ?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜