在java中打印出与我的正则表达式匹配的字符串? [英] Print out the string that matched my regular expression in java?

查看:98
本文介绍了在java中打印出与我的正则表达式匹配的字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复: 在 java 中打印正则表达式匹配

我在 java 中使用 Matcher 类将字符串与特定的正则表达式匹配,我使用 Pattern 类将其转换为 Pattern.我知道我的正则表达式有效,因为当我执行 Matcher.find() 时,我得到了我应该得到的真实值.但是我想打印出产生这些真实值的字符串(意思是打印出与我的正则表达式匹配的字符串)并且我在匹配器类中没有看到实现这一点的方法.请让我知道是否有人以前遇到过这样的问题.我很抱歉,因为这个问题相当初级,但我对正则表达式还很陌生,因此我仍在探索正则表达式世界.

I am using Matcher class in java to match a string with a particular regular expression which I converted into a Pattern using the Pattern class. I know my regex works because when I do Matcher.find(), I am getting true values where I am supposed to. But I want to print out the stings that are producing those true values (meaning print out the strings that match my regex) and I don't see a method in the matcher class to achieve that. Please do let me know if anyone has encountered such a problem before. I apologize as this question is fairly rudimentary but I am fairly new to regex and hence am still finding my way around the regex world.

推荐答案

假设 m 是你的匹配器:

Assuming mis your matcher:

m.group() 将返回匹配的字符串.

m.group() will return the matched string.

添加了有关匹配组的信息

Added info regarding matched groups

此外,如果您的正则表达式在括号内有部分,m.group(n) 将返回与括号内的第 n 个组匹配的字符串;

Also, if your regex has portions inside parenthesis, m.group(n) will return the string that matches the nth group inside parenthesis;

Pattern p = Pattern.compile("mary (.*) bob");
Matcher m = p.matcher("since that day mary loves bob");

m.group() 返回玛丽爱鲍勃".
m.group(1) 返回loves".

m.group() returns "mary loves bob".
m.group(1) return "loves".

这篇关于在java中打印出与我的正则表达式匹配的字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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