如何在java中使用正则表达式在字符之间的字符串中查找值
我正在尝试使用正则表达式在表中查找一些速率,这些正则表达式是从HTML读入字符串的。以下是一个例子:如何在java中使用正则表达式在字符之间的字符串中查找值,java,regex,Java,Regex,我正在尝试使用正则表达式在表中查找一些速率,这些正则表达式是从HTML读入字符串的。以下是一个例子: <td>Euro</td> <td class='rtRates'><a href='/graph/?from=USD&to=EUR'>0.772199</a></td> <td class='rtRates'><a href='/graph/?from=EUR&to=USD
<td>Euro</td>
<td class='rtRates'><a href='/graph/?from=USD&to=EUR'>0.772199</a></td>
<td class='rtRates'><a href='/graph/?from=EUR&to=USD'>1.295003</a></td>
您可以使用此表达式进行快速和脏搜索:
EUR'>([^<]*)<
EUR'>([^要仅匹配数字,请使用正向环视:
(?<=EUR'>)\\d+(?:\\.\\d*)?(?=<)
(?<=USD'>)\\d+(?:\\.\\d*)?(?=<)
(?)\\d+(?:\\.\\d*)(?=好的,不是你要求的,但我想指出的是,当你要查找的字符串的两边都是这样固定的时候,你可以使用substring()和indexOf()方法,这两种方法通常更容易调试:
public class substring_not_regex {
public static void main(String args[])
{
String test= "<td class='rtRates'><a href='/graph/?from=EUR&to=USD'>1.295003</a></td>";
String result = getConversion(test,"to=USD'>");
System.out.println("The result is: " + result);
test= "<td class='rtRates'><a href='/graph/?from=USD&to=EUR'>0.772199</a></td>";
; result = getConversion(test,"to=EUR'>");
System.out.println("The result is: " + result);
}
static String getConversion(String tableLine,String toSearchFor)
{
String value = "";
String aref_terminator = "</a>";
int position = tableLine.indexOf(toSearchFor);
if ( position == -1 ) return value;
int start_position = position + toSearchFor.length();
int end_position = tableLine.indexOf(aref_terminator,start_position);
if ( end_position == -1 ) return value;
value = tableLine.substring(start_position,end_position);
return value;
}
}
也许您可以向我们展示您迄今为止所做的工作。提供一个代码示例将是一个良好的开端。@user1745719您应该只在您至少尝试自己创建代码时发布有关代码的问题。每个人都在这里提供帮助,但不是为您编写代码。尝试使用正则表达式解析HTML几乎在所有情况下都是错误的。请使用HTML解析器相关:@BrianRoach。谢谢你的链接,不幸的是,我这次不得不使用正则表达式。我确实更喜欢HTML解析器方法。好吧,但是正则表达式代码应该包括在内。即使它不起作用,人们也可以解释你做错了什么。现在,没有办法告诉你。请考虑编辑你的文章现在开始,并将java正则表达式添加到其中。重新编写东西,而不是我需要,说我正在尝试。这样的事情会产生很大的不同。在我学会之前,我在所有帖子上都被记了下来。这确实有助于准备我不认为有理由包含@Ωmega我通常添加它来说明字符串必须包含@dasblinkenlight的这一点谢谢你的帮助,这很好。Regex伤害了我的大脑!
public class substring_not_regex {
public static void main(String args[])
{
String test= "<td class='rtRates'><a href='/graph/?from=EUR&to=USD'>1.295003</a></td>";
String result = getConversion(test,"to=USD'>");
System.out.println("The result is: " + result);
test= "<td class='rtRates'><a href='/graph/?from=USD&to=EUR'>0.772199</a></td>";
; result = getConversion(test,"to=EUR'>");
System.out.println("The result is: " + result);
}
static String getConversion(String tableLine,String toSearchFor)
{
String value = "";
String aref_terminator = "</a>";
int position = tableLine.indexOf(toSearchFor);
if ( position == -1 ) return value;
int start_position = position + toSearchFor.length();
int end_position = tableLine.indexOf(aref_terminator,start_position);
if ( end_position == -1 ) return value;
value = tableLine.substring(start_position,end_position);
return value;
}
}
The result is: 1.295003
The result is: 0.772199