我为波斯语字符串编写了一个自定义TextView,这个TextView应该将英文数字替换为波斯数字
public class PersianTextView extends TextView {
public PersianTextView(Context context) {
super(context);
}
public PersianTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public PersianTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
@Override
public void setText(CharSequence text, BufferType type) {
String t = text.toString();
t = t.replaceAll("0", "۰");
t = t.replaceAll("1", "۱");
t = t.replaceAll("2", "۲");
t = t.replaceAll("3", "۳");
t = t.replaceAll("4", "۴");
t = t.replaceAll("5", "۵");
t = t.replaceAll("6", "۶");
t = t.replaceAll("7", "۷");
t = t.replaceAll("8", "۸");
t = t.replaceAll("9", "۹");
super.setText((CharSequence)t, type);
}
}
此视图正常工作,但如果我从HTML设置文本,包含英文数字的链接将不会显示为链接! 什么是解决问题最简单的方法?
答案 0 :(得分:5)
需要以某种形式在链接上进行模式匹配。
private static final Pattern DIGIT_OR_LINK_PATTERN =
Pattern.compile("(\\d|https?:[\\w_/+%?=&.]+)");
// Pattern: (dig|link )
private static final Map<String, String> PERSIAN_DIGITS = new HashMap<>();
static {
PERSIAN_DIGITS.put("0", "۰");
PERSIAN_DIGITS.put("1", "۱");
PERSIAN_DIGITS.put("2", "۲");
PERSIAN_DIGITS.put("3", "۳");
PERSIAN_DIGITS.put("4", "۴");
PERSIAN_DIGITS.put("5", "۵");
PERSIAN_DIGITS.put("6", "۶");
PERSIAN_DIGITS.put("7", "۷");
PERSIAN_DIGITS.put("8", "۸");
PERSIAN_DIGITS.put("9", "۹");
}
public static String persianDigits(String s) {
StringBuffer sb = new StringBuffer();
Matcher m = DIGIT_OR_LINK_PATTERN.matcher(s);
while (m.find()) {
String t = m.group(1);
if (t.length() == 1) {
// Digit.
t = PERSIAN_DIGITS.get(t);
}
m.appendReplacement(sb, t);
}
m.appendTail(sb);
return sb.toString();
}
P.S。
根据文字的不同,最好只替换HTML标记之外的数字,即>
和<
之间的数字。
private static final Pattern DIGIT_OR_LINK_PATTERN =
Pattern.compile("(\\d|<[^>]*>)",
Pattern.DOTALL|Pattern.MULTILINE);
答案 1 :(得分:1)
试试这个,不检查是否有效:
String t = text.toString();
// separate input by spaces ( URLs don't have spaces )
String [] parts = t.split("\\s+");
t="";
// Attempt to convert each item into an URL.
for( String item : parts ) try {
URL url = new URL(item);
t+=item + " ";
} catch (MalformedURLException e) {
String temp = item;
item.replaceAll("0", "۰");
etc.
etc.
t+=item + " ";
}
super.setText((CharSequence)t, type);
答案 2 :(得分:1)
public String persianNumbers(String englishNumber) {
StringBuilder builder = new StringBuilder();
String str = englishNumber;
char[] persianChars = {'\u0660', '\u0661', '\u0662', '\u0663', '\u0664', '\u0665', '\u0666', '\u0667', '\u0668', '\u0669'};
for (int i = 0; i < str.length(); i++) {
if (Character.isDigit(str.charAt(i))) {
builder.append(persianChars[(int) (str.charAt(i)) - 48]);
} else {
builder.append(str.charAt(i));
}
}
System.out.println("Number in English : " + str);
System.out.println("Number In Persian : " + builder.toString());
return builder.toString();
}