2013-01-14 41 views
-3

我有一个这样的字符串:如何获得通过int值在HTML

static String name = "what is the language used in android <img height=\""+height+"\" width=\""+width+"\">"; 

我需要得到heightwidth的价值,这是我想过去的fly.Now我在我需要根据单个项目获取值的情况。

我试过正则表达式,但他们不工作。

+1

你有高度和宽度放的字符串中。你为什么不使用它们? – nhahtdh

+0

@nhahtdh是的,但我传递的高度和widht在飞,我处于一种情况下,我nedd基于单个项目获得这些值 – Goofy

+0

如何区分不同的项目呢?无论如何,正则表达式只会抓住所有人。 – nhahtdh

回答

1

您可以使用此:

int height = 0; 
int width = 0; 

Pattern h = Pattern.compile("height=\"([0-9]*)\""); 
Pattern w = Pattern.compile("width=\"([0-9]*)\""); 

Matcher m1 = h.matcher(name); 
Matcher m2 = w.matcher(name); 

if (m1.find()) { 
    height = Integer.parseInt(m1.group(1)); 
} 

if (m2.find()) { 
    width = Integer.parseInt(m2.group(1)); 
} 

System.out.println(height); 
System.out.println(width); 
+0

这将无法正常工作。字符串类“匹配”函数与其他语言的工作方式不同。 – nhahtdh

+0

@nhahtdh不同的是如何? – ATOzTOA

+0

它会检查整个字符串是否与正则表达式匹配。就像在开始和结束时把'^ $'放入正则表达式一样。您也无法访问捕获的文本,因为此方法仅用于验证。 – nhahtdh

0

我相信这应该得到高度的工作:

(?<=height=")[^"]*(?=")|(?<=height=')[^']*(?=') 

然后,你可以用宽度取代的height两个实例在正则表达式来获得的宽度。

这可能也是工作,更加简洁:

(?<=height=("|')).*?(?=\1) 
+0

如何使用此? – Goofy

+0

对于第二部分,您可能的意思是'[^'] *'而不是'[^“] *' – nhahtdh

+0

@nhahtdh是的,这就是我的意思,已更正,谢谢 – JLRishe

1

试试这个简单的正则表达式:

<img\s+height="(\d+)"\s+width="(\d+)"\s*> 

和尤尔代码:

List<String> matchList = new ArrayList<String>(); 

Pattern regex = Pattern.compile("<img\\s+height=\"(\\d+)\"\\s+width=\"(\\d+)\"\\s*>"); 
Matcher regexMatcher = regex.matcher(inputString); 
while (regexMatcher.find()) { 
    matchList.add(regexMatcher.group(1)); 

解释:

\d 匹配任何十进制数字。

\s 匹配任何空白字符。

(subexpression) 捕获匹配的子表达式

+0

就这样,你只能从字符串中获得高度。 – nhahtdh