Regular Expression to determine a string containing a certain form and parse it into an image
This is used when I write QQ expressions. I will discuss it separately.
First, put 0 to 106 images in res and name them F000 to F106.
Define a method in the program. <喎?http: www.bkjia.com kf ware vc " target="_blank" class="keylink"> VcD4KPHA + forward + ClN0cmluZyBzdHIgPSBtc2c7Ci8vz/forward = "f0 [0-9] {2} | f10 [0-7]"; // regular expression used to determine whether there is an expression in the message
Try {
SpannableString spannableString = ExpressionUtil. getExpressionString (context, str, zhengze );
Content. setText (spannableString );
} Catch (Exception e ){
E. printStackTrace ();
}
}
The ExpressionUtil class is like this.
Public class ExpressionUtil {
/**
* Perform regular expression determination on spanableString. If this parameter is met, replace it with an emoticon image.
*/
Public static void dealExpression (Context context, SpannableString spannableString, Pattern patten, int start) throws SecurityException, NoSuchFieldException, NumberFormatException, IllegalArgumentException, IllegalAccessException {
Matcher matcher = patten. matcher (spannableString );
While (matcher. find ()){
String key = matcher. group ();
If (matcher. start () <start ){
Continue;
}
Field field = R. drawable. class. getDeclaredField (key );
Int resId = Integer. parseInt (field. get (null). toString (); // generate the image resource id by matching the string above.
If (resId! = 0 ){
Bitmap bitmap = BitmapFactory. decodeResource (context. getResources (), resId );
ImageSpan imageSpan = new ImageSpan (bitmap); // obtain bitmap Using the image resource id, which is packaged with an ImageSpan
Int end = matcher. start () + key. length (); // calculate the length of the image name, that is, the length of the string to be replaced.
SpannableString. setSpan (imageSpan, matcher. start (), end, Spannable. SPAN_INCLUSIVE_EXCLUSIVE); // Replace the image with the specified position in the string
If (end <spannableString. length () {// if the entire string has not been verified, continue ..
DealExpression (context, spannableString, patten, end );
}
Break;
}
}
}
/**
* Get A SpanableString object. Use the input string and perform regular expression judgment.
* @ Param context
* @ Param str
* @ Return
*/
Public static SpannableString getExpressionString (Context context, String str, String zhengze ){
SpannableString spannableString = new SpannableString (str );
Pattern sinaPatten = Pattern. compile (zhengze, Pattern. CASE_INSENSITIVE); // generate a pattern using the input regular expression.
Try {
DealExpression (context, spannableString, sinaPatten, 0 );
} Catch (Exception e ){
Log. e ("dealExpression", e. getMessage ());
}
Return spannableString;
}
Through this judgment setting, you can convert some strings with F000 in the string to my image QQ expression.