[英]Regex Pattern, Matcher, split or pattern.split() which is the most efficient
我目前正在嘗試通過獲取信息的方式來提高應用程序的速度。
我讀了一個HTML頁面,從中可以獲取URL
和其他信息。 為此,我主要使用String.contains()
和String.split()
。 但是我想知道什么是最有效的方法。 我看了一下,嘗試了一些,但結果對我來說是非常相似的:/
這是我的一些代碼(部分僅用於測試):
Pattern p = Pattern.compile("\" title=\"Read ");
//Pattern p2 = Pattern.compile("Online\">");
//Pattern p3 = Pattern.compile("</a></th>");
Pattern p4 = Pattern.compile("Online\">(.*)</a></th>");
while ((inputLine = in.readLine()) != null)
{
if(inputLine.contains("<table id=\"updates\">"))
{
tmp = inputLine.split("<tr><th><a href=\"");
for(String s : tmp)
{
if(s.contains("\" title=\"Read "))
{
//url = s.split("\" title=\"Read ")[0].replace(" ", "%20");
//name = s.split("Online\">")[1].split("</a></th>")[0];
url = p.split(s)[0].replace(" ", "%20");
//name = p3.split(p2.split(s)[1])[0];
Matcher matcher = p4.matcher(s);
while(matcher.find())
name = matcher.group(1);
array.add(new Object(name, url));
}
}
break;
}
}
如您所見,我在這里嘗試過Pattern
, Matcher
, split
或pattern.split()
但是我也知道這里有replaceAll or replaceFirst
。
在這種情況下,最適合您的方法是什么?
非常感謝。
PS:我在這里閱讀: http : Pattern.split
比split()
更好,但我找不到更大的基准。
-----更新----
Pattern p1 = Pattern.compile("\" title=\"Read ");
Pattern p2 = Pattern.compile("Online\">(.*?)</a></th>");
Matcher matcher = p2.matcher("");
while( (inputLine = in.readLine()) != null)
{
if( (tmp = inputLine.split("<tr><th><a href=\"")).length > 1 )
{
for(String s : tmp)
{
if(s.contains("\" title=\"Read "))
{
url = p1.split(s)[0].replace(" ", "%20");
if(matcher.reset(s).find())
name = matcher.group(1);
arrays.add(new Object(name, url));
}
}
break;
}
}
使用正則表達式的任何字符串功能(它們是matches(s)
replaceAll(s,s)
replaceFirst(s,s)
split(s)
,和split(s,i)
編譯的正則表達式,並創建一個Matcher 每次對象,在循環中使用時效率很低。
如果需要加快速度,第一步是停止使用String函數,而直接使用Pattern和Matcher。 這是我演示此問題的答案 。
理想情況下,正如我在此答案中所描述的,您應該只創建一個Matcher對象 。
有關正則表達式的更多信息,請查看常見問題解答
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.