I have a String that is something like this:
A20130122.0000+0000-0015+0000_name
Then I would like to extract this information:
The 20130122.0000+0000-0015+0000
that will be parsed to a date later on. And the final part which is name
.
So I am using in Java something like this:
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);
But I am getting a java.lang.IllegalStateException: No match found
Do you know what I am doing wrong?
You aren't calling Matcher#find
or Matcher#matches
methods after this line:
Matcher m = p.matcher(theString);
Try this code:
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
will throw IllegalStateException
if the matcher's regex hasn't yet been applied to its target text, or if the previous application was not successful.
Matcher#find
applies the matcher's regex to the current region of the matcher's target text, returning a Boolean indicating whether a match is found.
You can try this :
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
Refer Grouping in REGEX
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.