Java正则表达式 [英] Java Regular expression

查看:93
本文介绍了Java正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个字符串和一个要在该字符串中搜索的模式.现在,当我匹配字符串中的模式时,我想知道与我的模式匹配的字符串.

I have a string and a pattern that I want to search for in that string. Now, when I match the pattern in the string, I want to know the string that matches my pattern.

String template = "<P ALIGN=\"LEFT\"><FONT FACE=\"Verdana\" SIZE=\"12\"> My Name is xyz </FONT></P>";

String pattern = "<FONT.*>";

Pattern.compile(pattern,Pattern.CASE_INSENSITIVE);

如何找到与模板中的模式匹配的字符串.

How can I find out the string that matches the pattern in my template.

即我想得到<FONT FACE=\"Verdana\" SIZE=\"12\">作为结果. Java中的正则表达式库提供了什么方法可以帮助我吗?

i.e I want to get <FONT FACE=\"Verdana\" SIZE=\"12\"> as the result. Is there any method provided by the regex library in Java which can help me?

可以匹配<FONT FACE=\"Verdana\" SIZE=\"12\"> My Name is xyz </FONT><LI><FONT FACE=\"Verdana\" SIZE=\"12\"> My Name is xyz </FONT></LI>的正则表达式是什么,并且在给定的文本中不应贪婪.

What is the regular expression that can match <FONT FACE=\"Verdana\" SIZE=\"12\"> My Name is xyz </FONT> and <LI><FONT FACE=\"Verdana\" SIZE=\"12\"> My Name is xyz </FONT></LI> and it should not be greedy in a given text.

推荐答案

您可以通过

You can access the matched part of the string through matcher.group() .

一种更精细的方法是使用matcher.group(1)来获得匹配的部分.

A more elaborate way is to use capturing groups. Put the part you want to "extract" from the matched string within parethesis, and then get hold of the matched part through, for instance matcher.group(1).

在您的特定示例中,您需要为*使用勉强限定符.否则,.*会一直匹配到字符串的末尾(因为它以P>结尾).

In your particular example, you need to use a reluctant qualifier for the *. Otherwise, the .* will match all the way to the end of the string (since it ends with P>).

为说明这两种用法,请分别使用 Matcher.group()

To illustrate both the use of Matcher.group() and Matcher.group(int):

String template = "<P ALIGN=\"LEFT\"><FONT FACE=\"Verdana\" SIZE=\"12\"> My Name is xyz </FONT></P>";
String pattern = "<FONT (.*?)>";

Pattern p = Pattern.compile(pattern, Pattern.CASE_INSENSITIVE);
Matcher m = p.matcher(template);

if (m.find()) {
    // prints: <FONT FACE="Verdana" SIZE="12"> My Name is xyz </FONT></P>
    System.out.println(m.group());

    // prints: FACE="Verdana" SIZE="12"
    System.out.println(m.group(1));
}

这篇关于Java正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆