[英]Regexp matching in group with special characters
我有一個像這樣的字符串:
A20130122.0000+0000-0015+0000_name
然后,我想提取此信息:
20130122.0000+0000-0015+0000
,將在以后解析為一個日期。 最后一部分是name
。
所以我在Java中使用這樣的東西:
String regexpOfdate = "[0-9]{8}\\.[0-9]{4}\\+[0-9]{4}-[0-9]{4}\\+[0-9]{4}";
String regexpOfName = "\\w+";
Pattern p = Pattern.compile(String.format("A(%s)_(%s)", regexpOfdate, regexpOfName));
Matcher m = p.matcher(theString);
String date = m.group(0);
String name = m.group(1);
但我收到java.lang.IllegalStateException: No match found
你知道我在做什么錯嗎?
您不會在此行之后調用Matcher#find
或Matcher#matches
方法:
Matcher m = p.matcher(theString);
試試這個代碼:
Matcher m = p.matcher(theString);
if (m.find()) {
String date = m.group(1);
String name = m.group(2);
System.out.println("Date: " + date + ", name: " + name);
}
如果尚未將匹配器的正則表達式應用於其目標文本,或者如果先前的應用程序未成功,則Matcher#group
將引發IllegalStateException
。
Matcher#find
將匹配器的正則表達式應用於匹配器目標文本的當前區域,並返回一個布爾值,指示是否找到匹配項。
您可以嘗試以下方法:
String theString="A20130122.0000+0000-0015+0000_name";
String regexpOfdate = "([0-9]{8})\\.[0-9]{4}\\+[0-9]{4}-[0-9]{4}\\+[0-9]{4}";
String regexpOfName = "(\\w+)";
Pattern p = Pattern.compile(String.format("A(%s)_(%s)", regexpOfdate, regexpOfName));
Matcher m = p.matcher(theString);
if(m.find()){
String date = m.group(2);
String name = m.group(3);
System.out.println("date: "+date);
System.out.println("name: "+name);
}
OUTPUT
date: 20130122
name: name
請參考REGEX中的分組
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.