Pattern / Matcher group()在Java中获取子字符串? [英] Pattern/Matcher group() to obtain substring in Java?

查看:76
本文介绍了Pattern / Matcher group()在Java中获取子字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

更新:感谢所有精彩的回复!我尝试了许多不同的正则表达式模式,但不明白为什么m.matches()没有做我认为它应该做的事情。当我切换到 m.find()时,以及调整正则表达式模式,我能够到达某个地方。

UPDATE: Thanks for all the great responses! I tried many different regex patterns but didn't understand why m.matches() was not doing what I think it should be doing. When I switched to m.find() instead, as well as adjusting the regex pattern, I was able to get somewhere.

我想匹配Java字符串中的模式,然后使用正则表达式提取匹配的部分(如Perl的$& operator)。

I'd like to match a pattern in a Java string and then extract the portion matched using a regex (like Perl's $& operator).

这是我的源字符串s: DTSTART; TZID = America / Mexico_City:20121125T153000
我想提取America / Mexico_City部分。

This is my source string "s": DTSTART;TZID=America/Mexico_City:20121125T153000 I want to extract the portion "America/Mexico_City".

我以为我可以使用Pattern和Matcher,然后使用m.group()提取但是它没有按照我的预期工作。我尝试使用不同的正则表达式字符串进行修改,而m.matches()上唯一似乎是。* TZID。*这是没有意义的,因为它只是返回整个字符串。有人可以开导我吗?

I thought I could use Pattern and Matcher and then extract using m.group() but it's not working as I expected. I've tried monkeying with different regex strings and the only thing that seems to hit on m.matches() is ".*TZID.*" which is pointless as it just returns the whole string. Could someone enlighten me?

 Pattern p = Pattern.compile ("TZID*:"); // <- change to "TZID=([^:]*):"
 Matcher m = p.matcher (s);
 if (m.matches ()) // <- change to m.find()
    Log.d (TAG, "looking at " + m.group ()); // <- change to m.group(1)


推荐答案

你使用 m.match()尝试匹配整个字符串,如果你将使用 m.find(),它将在里面搜索匹配,我也改进了你的正则表达式以使用零宽度后面的方式排除TZID前缀:

You use m.match() that tries to match the whole string, if you will use m.find(), it will search for the match inside, also I improved a bit your regexp to exclude TZID prefix using zero-width look behind:

     Pattern p = Pattern.compile("(?<=TZID=)[^:]+"); //
     Matcher m = p.matcher ("DTSTART;TZID=America/Mexico_City:20121125T153000");
     if (m.find()) {
         System.out.println(m.group());
     }

这篇关于Pattern / Matcher group()在Java中获取子字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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