Print out the string that matched my regular expression in java?

落爺英雄遲暮 提交于 2019-12-08 09:31:01

问题


Possible duplicate: Print regex matches in java

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.


回答1:


Assuming mis your matcher:

m.group() will return the matched string.

[EDIT] Added info regarding matched groups

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() returns "mary loves bob".
m.group(1) return "loves".



来源:https://stackoverflow.com/questions/11910834/print-out-the-string-that-matched-my-regular-expression-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!