简体   繁体   English

通过正则表达式在Android中制作对象

[英]Making objects in Android from regex

I am writing an Android application which gets string to parse using regex. 我正在编写一个Android应用程序,该应用程序使用正则表达式获取要解析的字符串。 Let's say it gets 假设它得到了

'Tis an example image of a beaver {[beaver.jpg]} having an afternoon tea.

And what I want to get is TextView with 'Tis an example image of a beaver , ImageView beaver.jpg and an another TextView having an afternoon tea. 我想得到的是带有TextView的'Tis an example image of a beaver ,ImageView beaver.jpg和另一个having an afternoon tea. TextView having an afternoon tea. .

How (if possible) is creating objects possible after reading such string and parsing with regex? 读取此类字符串并使用正则表达式进行解析后,如何(如果可能)创建对象?

Your custom view class should have a constructor that takes three String parameters, one for the path of the image, one for text to be displayed before the image and one for the text to display afterwards. 您的自定义视图类应具有一个构造函数,该构造函数采用三个String参数,一个用于图像的路径,一个用于在图像之前显示的文本,一个用于在图像之后显示的文本。

class YourView { 
    public YourView(String imgPath, String beforeImg, String afterImg){ 
         //add TextView for text before image 
         //add ImageView for image 
         //add TextView for text after image 
    }
}

If your image will always be enclosed in a {[ ]} , the regex (.+)\\\\{\\\\[(.+)\\\\]\\\\}(.+) will capture everything before the {[ in capturing group 0, everything between {[ and }] (ie the image path) in group 1, and everything after }] in group 2. 如果您的图片始终包含在{[ ]} ,则正则表达式(.+)\\\\{\\\\[(.+)\\\\]\\\\}(.+)将捕获{[在捕获组中0,组1中{[}]之间的所有内容(即图像路径),以及组2中}]之后的所有内容。

If you use a Java Matcher You can then achieve your desired result like: 如果使用Java Matcher可以实现所需的结果,例如:

    String pre, path, post; 
    while (matcher.find()){ 
        pre = matcher.group(0);
        path = matcher.group(1);
        post = matcher.group(2); 
        YourView view = new YourView(path, pre, post); 
        //add view 
    }

Note that, if the image is at the end or beginning of the text, you'll simply be passing empty strings as the third/first parameters here, which will result in the creation of empty TextViews, which should be harmless (or you can do a check and not create one for empty strings). 请注意,如果图像位于文本的末尾或开头,则只需在此处传递空字符串作为第三个/第一个参数,这将导致创建空的TextView,这应该是无害的(或者您可以进行检查,而不为空字符串创建一个检查)。

That said, also note that above code is untested (but should give you the general idea), and that I'm a Java programmer with little experience in Android - so let me know if there's an Android-specific reason this wouldn't work 也就是说,还请注意,上面的代码未经测试(但应该可以带给您总体思路),而且我是一位Java程序员,对Android的经验很少,所以请告诉我是否有Android特定的原因,这是行不通的

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM