how to remove last value from char array

Viewed 86

How to remove last white space from the string. I am reading the html code. here I want to read only 'Remove a Speed Dial: Tap the'. This is my expected output. In my code I used the trim() also. but by using below code, I am getting output as 'Remove a Speed Dial: Tap the '

   in html text is "Remove a Speed Dial: Tap the "
   String str = new String(data);
   System.out.println(Arrays.toString(data));
   System.out.println(str.trim());

  output:
  [R, e, m, o, v, e,  , a,  , S, p, e, e, d,  , D, i, a, l, :,  , T, a, p,  , t, h, e,  ]
  Remove a Speed Dial: Tap the 
1 Answers

If you only want to match the last &nbsp then the following regex should be able to match it \p{Z}(?!.*\p{Z}) which if combined with

string.replaceAll("\\p{Z}(?!.*\\p{Z})","")

or if encoded

string.replaceAll(" (?!.* )","")

will remove only the last white space or invisible separator character if using \P{Z} which &nbsp is apart of, or will removed only the last   if only looking for the encoded version.

Be careful if using the \P{Z} as if there is a trailing whitespace that will be returned instead of the &nbsp


  • \p{z} - matches any kind of white space or invisible separator which includes &nbsp
  • (?!.*\p{Z}) - uses a negative look ahead which matches all of the white spaces or invisible separators before the last occurrence and consumes them so only the final occurrence is returned by the regex

EDIT: i checked &nbsp is included

Related