[英]How to search a SpannableString without knowing the exact substring
我想搜索一个可跨越的字符串以找到某个我不知道长度或确切字符的某个子字符串的索引,例如[size=??]
其中问号可以是任何字符或任何长度的子字符串。 如果可能,我还想知道找到的此类字符串的长度。
(编辑)示例:如果给出了诸如"string [size=212] more string"
,我希望它返回索引,因此在本例中为7
和[size=212]
的长度,在本例中为10
您需要使用正则表达式来提取子字符串。 获得它后,使用函数 indexOf 进行搜索匹配,这将为您提供子字符串出现的第一个索引。
注意:请为您的问题提供更多详细信息
您可以使用Pattern和Matcher来完成这项工作。
public class Main
{
public static void main(String[] args)
{
String str = "string [size=212] more string [size=212] more string here";
Pattern pat = Pattern.compile("\\[size=[0-9]+\\]");
Matcher mat = pat.matcher(str);
int index, lastIndex = 0, length, value;
while(mat.find()) {
final String found = mat.group(0);
value = Integer.parseInt(found.replaceAll("^\\[size=|\\]$", ""));
length = found.length();
index = str.indexOf(found, lastIndex);
lastIndex += length;
System.out.printf("index: %d, length: %d, string: %s, value: %d%n", index, length, found, value);
}
}
}
输出:
index: 7, length: 10, string: [size=212], value: 212
index: 30, length: 10, string: [size=212], value: 212
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.