问题描述
public static void main(String[] args) {// TODO Auto-generated method stubPattern pat = Pattern.compile("<img (.*)alt*>");@SuppressWarnings("resource")Scanner scanner = new Scanner(System.in);String input = scanner.nextLine();Matcher mat = pat.matcher(input);boolean resulet= mat.find();if (resulet == true){System.out.println("yes, i find it");}else System.out.println("no");} 我输入的是<img src="img.iknow.bdimg.com/jctuijian/0721/jctj.jpg?t=1405910012" alt=""> 没有匹配到这个,麻烦各位了。
解决方案
import java.util.Scanner;import java.util.regex.Matcher;import java.util.regex.Pattern;public class App {//<img src="img.iknow.bdimg.com/jctuijian/0721/jctj.jpg?t=1405910012" alt=""> public static void main(String[] args) {String imgRegex = "<img[^>]+src\s*=\s*['"]([^'"]+)['"][^>]*>";//String imgRegex = "<img(\s+.*?)(?:src\s*=\s*(?:'|")(.*?)(?:'|"))(.*?)/>"Pattern pat = Pattern.compile(imgRegex);Scanner scanner = new Scanner(System.in);String input = scanner.nextLine();Matcher mat = pat.matcher(input);boolean resulet = mat.find();if (resulet == true) {System.out.println("yes, i find it");} elseSystem.out.println("no");}}
解决方案二:
最简单的匹配正则 <(img)(s*[a-zA-Z]*=(['"]).*3)*>.*</1>
解决方案三:
package cn.com.wangxiuwei.test;import java.util.Scanner; import java.util.regex.Matcher; import java.util.regex.Pattern; public class TestRegex{ public static void main(String[] args) { String imgRegex = "<img[^>]+src=".*?"(\s)+?alt=".*?">"; Pattern pat = Pattern.compile(imgRegex); Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); Matcher mat = pat.matcher(input); boolean resulet = mat.find(); if (resulet == true) { System.out.println("yes, i find it"); } else System.out.println("no"); } } 楼主多多写写就会了
解决方案四:
String regex = "<img(\s)+?src=".*?"(\s)+?alt=".*?">";//"<img.*?>";Pattern pattern = null;Matcher matcher = null;try {pattern = Pattern.compile(regex, Pattern.CASE_INSENSITIVE);matcher = pattern.matcher(str);while (matcher.find()) {System.out.println("=====find it.======");}} catch (PatternSyntaxException e) {e.printStackTrace();System.exit(0);}
解决方案五:
public static void main(String[] args) { Pattern pat = Pattern.compile("<img[^>]+src="([^"]+)"); Scanner scanner = new Scanner(System.in); String input = scanner.nextLine(); Matcher mat = pat.matcher(input); boolean resulet = mat.find(); if (resulet == true) { System.out.println("yes, i find it"); } else System.out.println("no"); }
解决方案六:
img后面你是不是有个空格哦
解决方案七:
Pattern pat = Pattern.compile("<img (.*)alt.*>");这样就可以了,最后面的*前加.不过针对具体的要求,最好优化,可以匹配的更准确。