[英]Using Regular Expressions
我在尝试使用我在 JavaScript 中使用的正则表达式时遇到问题。 在网页上,您可能有:
<b>Renewal Date:</b> 03 May 2010</td>
我只是希望能够抽出 2010 年 5 月 3 日,记住一个网页不仅仅包含上述内容。 我目前使用 JavaScript 执行此操作的方式是:
DateStr = /<b>Renewal Date:<\/b>(.+?)<\/td>/.exec(returnedHTMLPage);
我试图按照一些关于java.util.regex.Pattern
和java.util.regex.Matcher
教程进行操作,但没有成功。 我似乎无法将(.+?)翻译成他们能理解的东西??
谢谢,
诺内尔
这就是 Java 中正则表达式的使用方式:
Pattern p = Pattern.compile("<b>Renewal Date:</b>(.+?)</td>");
Matcher m = p.matcher(returnedHTMLPage);
if (m.find()) // find the next match (and "generate the groups")
System.out.println(m.group(1)); // prints whatever the .+? expression matched.
Matcher 类中还有其他有用的方法,例如m.matches()
。 看看Matcher 。
matches
与find
问题是您在应该使用find
时使用了matches
。 从API :
matches
方法尝试将整个输入序列与模式进行匹配。find
方法扫描输入序列,寻找与模式匹配的下一个子序列。
请注意, String.matches(String regex)
还会查找整个字符串的完整匹配项。 不幸的是String
不提供部分正则表达式匹配,但你总是可以s.matches(".*pattern.*")
代替。
Java 完全理解(.+?)
。
这是一个演示:给定一个字符串s
,它由至少重复两次的字符串t
组成。 找到t
。
System.out.println("hahahaha".replaceAll("^(.+)\\1+$", "($1)"));
// prints "(haha)" -- greedy takes longest possible
System.out.println("hahahaha".replaceAll("^(.+?)\\1+$", "($1)"));
// prints "(ha)" -- reluctant takes shortest possible
还应该说您不必要地将\\
注入了正则表达式( "\\\\"
作为 Java 字符串文字)。
String regexDate = "<b>Expiry Date:<\\/b>(.+?)<\\/td>";
^^ ^^
Pattern p2 = Pattern.compile("<b>Expiry Date:<\\/b>");
^^
\\
用于转义正则表达式元字符。 A /
不是正则表达式元字符。
好的,所以使用 aioobe 的原始建议(我之前也尝试过),我有:
String regexDate = "<b>Expiry Date:</b>(.+?)</td>";
Pattern p = Pattern.compile(regexDate);
Matcher m = p.matcher(returnedHTML);
if (m.matches()) // check if it matches (and "generate the groups")
{
System.out.println("*******REGEX RESULT*******");
System.out.println(m.group(1)); // prints whatever the .+? expression matched.
System.out.println("*******REGEX RESULT*******");
}
IF 语句必须不断出现 FALSE,因为 *******REGEX RESULT******* 永远不会输出。
如果有人错过了我想要实现的目标,我只是想确定日期。 在 html 页面中有一个类似<b>Expiry Date:</b> 03 May 2010</td>
,我想要 2010 年 5 月 3 日。
(.+?)
是一个奇怪的选择。 试试( *[0-9]+ *[A-Za-z]+ *[0-9]+ *)
或者只是([^<]+)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.