Roshnal
Roshnal

Reputation: 1314

Escape characters displayed in TextView

In an Android app I'm making, I construct a TextView programmatically and pass a String to setText. The String I'm passing is obtained from another source, and it contains escape characters. Here's an example String:

AxnZt_35\/435\/46\/34

The \/ should in fact be just /. But the TextView displays the whole thing exactly as in the above example.

The code I'm using to construct the TextView:

TextView textView = new TextView(context);
textView.setText(text);
textView.setTextColor(color);
textView.setTypeface(Typeface.DEFAULT_BOLD);
textView.setTextSize(14);

So my question is, how can I not display the extra \? I just want the above example displayed as:

AxnZt_35/435/46/34

Thanks.

EDIT

The String I provided above is just an example. There might be other characters in the String. For example, the character / or \ by itself is perfectly valid. The problem is that / is displayed as \/.

Upvotes: 1

Views: 1859

Answers (3)

SlumpA
SlumpA

Reputation: 892

Run this as plain Java

public class Klass{

    public static void main(String[] args) {
        System.out.println(new String("\\/"));
        System.out.println(new String("\\/").replaceAll("/", ""));
        System.out.println(new String("\\/").replaceAll("\\/", ""));
        System.out.println(new String("\\/").replaceAll("\\\\/", ""));
    }

}

The regex for \ is "\\": in regex one pair of \ is equal to one \ in the new String()

Upvotes: 0

Daniel Nugent
Daniel Nugent

Reputation: 43322

The answer from @Numan1617 is close, but for escape characters and replaceAll(), you have to escape them twice.

See This Post.

So, the correct code in this case would be:

    String str = "AxnZt_35\\/435\\/46\\/34";

    System.out.println(str); //prints AxnZt_35\/435\/46\/34

    String s2 = str.replaceAll("\\\\/", "/"); 

    System.out.println(s2); //prints AxnZt_35/435/46/34

Upvotes: 1

Numan1617
Numan1617

Reputation: 1178

You'll have to replace all occurances of the \ before setting the text by using Strings replaceAll method:

textView.setText(text.replaceAll("\\", ""));

Upvotes: 0

Related Questions