// strings/StartEnd.java// (c)2017 MindView LLC: see Copyright.txt// We make no guarantees that this code is fit for any purpose.// Visit http://OnJava8.com for more book information.import java.util.regex.*;public class StartEnd {public static String input ="As long as there is injustice, whenever a\n" +"Targathian baby cries out, wherever a distress\n" +"signal sounds among the stars " +"... We'll be there.\n"+"This fine ship, and this fine crew ...\n" +"Never give up! Never surrender!";private static class Display {private boolean regexPrinted = false;private String regex;Display(String regex) { this.regex = regex; }void display(String message) {if(!regexPrinted) {System.out.println(regex);regexPrinted = true;}System.out.println(message);}}static void examine(String s, String regex) {Display d = new Display(regex);Pattern p = Pattern.compile(regex);Matcher m = p.matcher(s);while(m.find())d.display("find() '" + m.group() +"' start = "+ m.start() + " end = " + m.end());if(m.lookingAt()) // No reset() necessaryd.display("lookingAt() start = "+ m.start() + " end = " + m.end());if(m.matches()) // No reset() necessaryd.display("matches() start = "+ m.start() + " end = " + m.end());}public static void main(String[] args) {for(String in : input.split("\n")) {System.out.println("input : " + in);for(String regex : new String[]{"\\w*ere\\w*","\\w*ever", "T\\w+", "Never.*?!"})examine(in, regex);}}}/* Output:input : As long as there is injustice, whenever a\w*ere\w*find() 'there' start = 11 end = 16\w*everfind() 'whenever' start = 31 end = 39input : Targathian baby cries out, wherever a distress\w*ere\w*find() 'wherever' start = 27 end = 35\w*everfind() 'wherever' start = 27 end = 35T\w+find() 'Targathian' start = 0 end = 10lookingAt() start = 0 end = 10input : signal sounds among the stars ... We'll bethere.\w*ere\w*find() 'there' start = 43 end = 48input : This fine ship, and this fine crew ...T\w+find() 'This' start = 0 end = 4lookingAt() start = 0 end = 4input : Never give up! Never surrender!\w*everfind() 'Never' start = 0 end = 5find() 'Never' start = 15 end = 20lookingAt() start = 0 end = 5Never.*?!find() 'Never give up!' start = 0 end = 14find() 'Never surrender!' start = 15 end = 31lookingAt() start = 0 end = 14matches() start = 0 end = 31*/
此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。
如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。