正則表示式常見匹配案例
阿新 • • 發佈:2019-01-23
匹配中文
[\u4E00-\u9FA5]
匹配空白行
\n\s*\r
匹配HTML標記
<(\S*?)[^>]*>.*?<^1>|<.*?/>
匹配URL
[a-zA-Z]+://[^\s]*
匹配國內電話(帶區號的如0668-7610110)
\d{3}-\d{8}|\d{4}-\d{7}
匹配騰訊的QQ號
[1-9][0-9]{4,}
匹配中國郵政編碼
[1-9]\d{5}(?!\d)
匹配身份證
\d{15}|\d{18}
匹配ip地址
\d+.\d+.\d+.\d+
從一個給定的字串中找到想要的字串:
public class RegexTest {
public static void main( String args[] ){
// 按指定模式在字串查詢
String line = "My name is Jianguotang。I am a Android programmer.I am 21 years old";
String pattern = "(\\D*)(\\d+)(.*)";
// 建立 Pattern 物件
Pattern r = Pattern.compile(pattern);
// 現在建立 matcher 物件
Matcher m = r.matcher(line);
if (m.find( )) {
System.out.println("Found value: " + m.group(0) );
System.out.println("Found value: " + m.group(1) );
System.out.println("Found value: " + m.group(2) );
System.out.println("Found value: " + m.group(3) );
} else {
System.out.println("NO MATCH");
}
}
}
執行結果
Found value: My name is Jianguotang。I am a Android programmer.I am 21 years old
Found value: My name is Jianguotang。I am a Android programmer.I am
Found value: 21
Found value: years old
假設您要替換一個字母后跟一個點或逗號的所有空格。
String pattern = "(\\w)(\\s+)([\\.,])";
System.out.println(EXAMPLE_TEST.replaceAll(pattern, ""));
替換標題標籤之間的文字
pattern = "(?i)(<title.*?>)(.+?)()";
String updated = EXAMPLE_TEST.replaceAll(pattern, "$2");
Pattern 和Matcher
您首先建立一個定義正則表示式的Pattern物件。此Pattern物件允許您為給定的字串建立Matcher物件。這個Matcher物件然後允許你對String進行正則表示式操作
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class RegexTestPatternMatcher {
public static final String EXAMPLE_TEST = "This is my small example string which I'm going to use for pattern matching.";
public static void main(String[] args) {
Pattern pattern = Pattern.compile("\\w+");
// 如果您想忽略大小寫敏感度,
// 你可以使用這個語句:
// Pattern pattern = Pattern.compile("\\s+", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(EXAMPLE_TEST);
// 檢查所有的結果
while (matcher.find()) {
System.out.print("Start index: " + matcher.start());
System.out.print(" End index: " + matcher.end() + " ");
System.out.println(matcher.group());
}
// 現在建立一個新的pattern和Matcher 以用選項卡替換空格s
Pattern replace = Pattern.compile("\\s+");
Matcher matcher2 = replace.matcher(EXAMPLE_TEST);
System.out.println(matcher2.replaceAll("\t"));
}
}
Start index: 0 End index: 4 This
Start index: 5 End index: 7 is
Start index: 8 End index: 10 my
Start index: 11 End index: 16 small
Start index: 17 End index: 24 example
Start index: 25 End index: 31 string
Start index: 32 End index: 37 which
Start index: 38 End index: 39 I
Start index: 40 End index: 41 m
Start index: 42 End index: 47 going
Start index: 48 End index: 50 to
Start index: 51 End index: 54 use
Start index: 55 End index: 58 for
Start index: 59 End index: 66 pattern
Start index: 67 End index: 75 matching
This is my small example string which I'm going to use for pattern matching.
建立一個連結檢查器
從網頁中提取所有有效的連結。它不考慮以“javascript:”或“mailto:”開頭的連結。
public class LinkGetter {
private Pattern htmltag;
private Pattern link;
public LinkGetter() {
htmltag = Pattern.compile("<a\\b[^>]*href=\"[^>]*>(.*?)</a>");
link = Pattern.compile("href=\"[^>]*\">");
}
public List<String> getLinks(String url) {
List<String> links = new ArrayList<String>();
try {
BufferedReader bufferedReader = new BufferedReader(
new InputStreamReader(new URL(url).openStream()));
String s;
StringBuilder builder = new StringBuilder();
while ((s = bufferedReader.readLine()) != null) {
builder.append(s);
}
Matcher tagmatch = htmltag.matcher(builder.toString());
while (tagmatch.find()) {
Matcher matcher = link.matcher(tagmatch.group());
matcher.find();
String link = matcher.group().replaceFirst("href=\"", "")
.replaceFirst("\">", "")
.replaceFirst("\"[\\s]?target=\"[a-zA-Z_0-9]*", "");
if (valid(link)) {
links.add(makeAbsolute(url, link));
}
}
} catch (MalformedURLException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return links;
}
private boolean valid(String s) {
if (s.matches("javascript:.*|mailto:.*")) {
return false;
}
return true;
}
private String makeAbsolute(String url, String link) {
if (link.matches("http://.*")) {
return link;
}
if (link.matches("/.*") && url.matches(".*$[^/]")) {
return url + "/" + link;
}
if (link.matches("[^/].*") && url.matches(".*[^/]")) {
return url + "/" + link;
}
if (link.matches("/.*") && url.matches(".*[/]")) {
return url + link;
}
if (link.matches("/.*") && url.matches(".*[^/]")) {
return url + link;
}
throw new RuntimeException("Cannot make the link absolute. Url: " + url
+ " Link " + link);
}
}
找到重複的單詞
以下正則表示式匹配重複的單詞。
\b(\w+)\s+\1\b
\ b是一個字邊界,\ 1引用了第一個組的捕獲匹配,即第一個字。 (?! - in)\ b(\ w +)\ 1 \ b如果不以“-in”開頭,則會找到重複的單詞。 提示:新增(?s)以跨多行搜尋
尋找從新行開始的元素
以下正則表示式允許您找到“標題”單詞,以防其在新行中開始。
(\n\s*)title