I have strings like that:
//RULE countryname=Brazil&useryear<=2017&usermonth<=01&userdayofmonth<=15 200
I want to fill an object I created like this:
public class Rule {
public List<String> countries;
public LocalDateTime fromTime;
public LocalDateTime toTime;
I used regex, but I wondered if there is a more elegant way to do so?
#Test
public void testRegex() throws Exception {
Pattern pattern = Pattern.compile(".*?flag\\((\\d+)\\)=true(.*)");
Matcher matcher = pattern.matcher("bbbbbbflag(27)=true 300");
while (matcher.find()) {
System.out.println("group 1: " + matcher.group(1));
}
pattern = Pattern.compile("(.*?)countryname=([\\w-]+)(.*)");
matcher = pattern.matcher("countryname=brazil ");
while (matcher.find()) {
System.out.println("group 2: " + matcher.group(2));
}
pattern = Pattern.compile(".*?countryname=(.*+)&.*]");
matcher = pattern.matcher("countryname=brazil&bllllll");
while (matcher.find()) {
System.out.println("group 1: " + matcher.group(1));
}
pattern = Pattern.compile(".*?useryear<=(\\d+)&usermonth<=(\\d+)&userdayofmonth<=(\\d+)(.*)");
matcher = pattern.matcher("useryear<=2017&usermonth<=01&userdayofmonth<=15");
while (matcher.find()) {
System.out.println("group 1: " + matcher.group(1));
System.out.println("group 2: " + matcher.group(2));
System.out.println("group 3: " + matcher.group(3));
}
}
You could combine your patterns with | and then look for all the matches:
String s = "//RULE countryname=Brazil&useryear<=2017&usermonth<=01&userdayofmonth<=15 200\n";
Pattern p = Pattern.compile("((countryname)=([\\w-]+)|(useryear)<=(\\d+)|(usermonth)<=(\\d+)|(userdayofmonth)<=(\\d+))");
Matcher m = p.matcher(s);
while(m.find()){
String type = "";
String value = "";
boolean first = true;
for(int i = 2; i<=m.groupCount(); i++){
String group = m.group(i);
if(first && group != null){
type = group;
first = false;
}else if(group != null){
value = group;
break;
}
}
System.out.println("Type: " + type + " Value: " + value);
}
Outputs:
Type: countryname Value: Brazil
Type: useryear Value: 2017
Type: usermonth Value: 01
Type: userdayofmonth Value: 15
You can do it without a regex. Since your string is similar to an http query with parameters, we can parse it in a similar manner to an http query. Please try if this example can help you.
package gnu;
import java.util.*;
import java.util.stream.Collectors;
import java.util.AbstractMap.SimpleImmutableEntry;
import static java.util.stream.Collectors.toList;
public class Main {
public static void main(String[] strg) {
String str = "//RULE countryname=Brazil&useryear<=2017&usermonth<=01&userdayofmonth<=15 200";
str = str.substring(str.indexOf(" ")+1, str.lastIndexOf(" "));
try {
ParseParams parse = new ParseParams();
Map<String, List<String>> map = parse.parseParams(str);
map.entrySet().forEach(entry -> {
System.out.println("Key : " + entry.getKey() + " Value : " + entry.getValue());
});
} catch (Throwable t) {
t.printStackTrace();
}
}
}
class ParseParams {
Map<String, List<String>> parseParams(String url) {
return Arrays.stream(url.split("&"))
.map(this::splitQueryParameter)
.collect(Collectors.groupingBy(SimpleImmutableEntry::getKey, LinkedHashMap::new, Collectors.mapping(Map.Entry::getValue, toList())));
}
private SimpleImmutableEntry<String, String> splitQueryParameter(String it) {
final int idx = it.indexOf("=");
String key = idx > 0 ? it.substring(0, idx) : it;
String value = idx > 0 && it.length() > idx + 1 ? it.substring(idx + 1) : null;
if (key.contains("<")) {
key = key.replace("<", "");
}
return new SimpleImmutableEntry<>(key, value);
}
}
Output
Key : countryname Value : [Brazil]
Key : useryear Value : [2017]
Key : usermonth Value : [01]
Key : userdayofmonth Value : [15]
Online demo.
Related
How can I check for an empty Optional array of strings in Java?
In the case is empty I would like to return a message.
#PostMapping("/users")
#ResponseBody
public String saveUsers(#RequestParam Optional<String>[] paramArray) {
System.out.println("param " + paramArray);
String msg = "";
int i = 0;
if (paramArray is empty) {
msg = "paramArray is empty";
} else {
for (Optional<String> paramArrayItem : paramArray) {
msg += "param[" + i + "]" + paramArrayItem + "\n";
i++;
}
}
return msg;
}
Optional<String>[] is an array of Optional<String> elements.
You'd rather want to have optional array of strings, so you need to change paramArray type to Optional<String[]>.
#PostMapping("/users")
#ResponseBody
public String saveUsers(#RequestParam Optional<String[]> paramArray) {
System.out.println("param " + paramArray);
String msg = "";
int i = 0;
if (paramArray.isEmpty()) {
msg = "paramArray is empty";
} else {
for (String paramArrayItem : paramArray.get()) {
msg += "param[" + i + "]" + paramArrayItem + "\n";
i++;
}
}
return msg;
}
Below is my else if ladder.
Please tell me how to optimize else if ladder using Map
for (String p1: data) {
p1 = p1.replace("#", "");
if (p1.startsWith("Year")) {
Year = p1.substring(p1.lastIndexOf(":") + 1);
System.out.print(Year);
} else if (p1.startsWith("Department")) {
Department = p1.substring(p1.lastIndexOf(":") + 1);
System.out.print(Department);
} else if (p1.startsWith("Division")) {
Division = p1.substring(p1.lastIndexOf(":") + 1);
System.out.print(Division);
} else if (p1.startsWith("Subject Code")) {
SubjectCode = p1.substring(p1.lastIndexOf(":") + 1);
System.out.print(SubjectCode);
} else if (p1.startsWith("Teacher Code")) {
int k = p1.indexOf(" ", p1.indexOf(" ") + 1);
String res = p1.substring(0, k);
System.out.print("Characters ::" + res);
String TeacherCode1 = p1.substring(p1.lastIndexOf(":") + 1);
int m = TeacherCode1.indexOf(" ", TeacherCode1.indexOf(" ") + 1);
System.out.println(m);
TeacherCode = TeacherCode1.substring(0, m);
System.out.println("Value of p2 ::" + TeacherCode.trim());
} else if (p1.startsWith("Date")) {
Date = p1.substring(p1.lastIndexOf(":") + 1);
System.out.print(Date);
}
}
The above code is too lengthy.
I want to optimize it for better performance using Map
Now I attached Image file,that i converted into text file using OCR and I wanted to split data,to save into database like Year:THIRD ,Department: INFO. TECH ,Date:18/08/2017,Subject Code: TBGOZ like that But in Optimize code using Map.
May be following will be helpful:
for (String p1: data)
{
p1 = p1.replace("#", "");
String[] vals = p1.split(":");
int lastIndx = vals.length-1;
switch(vals[0])
{
case "Year":
Year = vals[lastIndx];
System.out.print(Year);
break;
case "Department":
Department = vals[lastIndx];
System.out.print(Department);
break;
case "Division":
Division = vals[lastIndx];
System.out.print(Division);
break;
case "Subject Code":
SubjectCode = vals[lastIndx];
System.out.print(SubjectCode);
break;
case "Date":
Date = vals[lastIndx];
System.out.print(Date);
break;
case "Teacher Code":
int k = p1.indexOf(" ", p1.indexOf(" ") + 1);
String res = p1.substring(0, k);
System.out.print("Characters ::" + res);
String TeacherCode1 = vals[lastIndx];;
int m = TeacherCode1.indexOf(" ", TeacherCode1.indexOf(" ") + 1);
System.out.println(m);
TeacherCode = TeacherCode1.substring(0, m);
System.out.println("Value of p2 ::" + TeacherCode.trim());
break;
}
}
The logic for Year, Department, Division, Subject Code and Date is the same.
So you can do the other parts first, and then else for these common bits
if (p1.startsWith("Teacher Code")) {
int k = p1.indexOf(" ", p1.indexOf(" ") + 1);
String res = p1.substring(0, k);
System.out.print("Characters ::" + res);
String TeacherCode1 = p1.substring(p1.lastIndexOf(":") + 1);
int m = TeacherCode1.indexOf(" ", TeacherCode1.indexOf(" ") + 1);
System.out.println(m);
TeacherCode = TeacherCode1.substring(0, m);
System.out.println("Value of p2 ::" + TeacherCode.trim());
} else {
String other = p1.substring(p1.lastIndexOf(":") + 1);
System.out.print(other);
}
BTW, "I want to optimize it for better performance using Map" - There will be no noticeable performance benefit.
As you may know, maps contain key value pairs. In this case, your keys will be strings like Year, Department, Division etc. I suggest you put these strings into an array, except the teacher code because that needs special handling:
String[] keys = {"Year", "Department", "Division" ...};
Now, create your map:
Map<String, String> map = new HashMap<>();
You can then loop through this array:
for (String key : keys) {
if (p1.startsWith("Teacher Code")) {
int k = p1.indexOf(" ", p1.indexOf(" ") + 1);
String res = p1.substring(0, k);
System.out.print("Characters ::" + res);
String TeacherCode1 = p1.substring(p1.lastIndexOf(":") + 1);
int m = TeacherCode1.indexOf(" ", TeacherCode1.indexOf(" ") + 1);
System.out.println(m);
map.put("Teacher Code", TeacherCode1.substring(0, m));
System.out.println("Value of p2 ::" + TeacherCode.trim());
} else if (p1.startsWith(key)) {
String value = p1.substring(p1.lastIndexOf(":") + 1);
map.put(key, value);
System.out.println(value);
}
}
If variable assignment is not important. here is how you can generate map.
Function<String, String> keyFunction = p1 -> {
return p1.substring(0, p1.indexOf(":") + 1);
};
Function<String, String> valueFunction = p1 -> {
return p1.substring(p1.lastIndexOf(":") + 1);
};
Map<String, String> map =data.stream().collect(Collectors.toMap(keyFunction, valueFunction));
How can I split a flat string based on 0102**? string tokenizer is working for only **. Is there any way to split based on 0102**? Please suggest
Here is my complete method
private String handleCibil(InterfaceRequestVO ifmReqDto, String szExtIntType) throws MalformedURLException, org.apache.axis.AxisFault, RemoteException {
/* Declaration and initiliazation */
ConfVO confvo = ifmReqDto.getExtConfVo();
String szResponse = null;
String cibilResponse = null;
String errorResponse = null;
String endpointURL = null;
long timeOut = confvo.getBurMgr().getBurInfo(szExtIntType).getTimeOut();
endpointURL = formWebServiceURL(confvo, szExtIntType);
URL url = new URL(endpointURL);
log.debug("Input xml for cibil "+ifmReqDto.getIfmReqXML());
BasicHttpStub stub= new BasicHttpStub(url,new org.apache.axis.client.Service());
szResponse = stub.executeXMLString(ifmReqDto.getIfmReqXML());
//szResponse=szResponse.replaceAll("&", "&");
log.debug("szResponse "+szResponse);
/* Validate if the obtained response is as expected by IFM */
try {
extDao = new ExtInterfaceXMLTransDAO(ifmReqDto.getSemCallNo(), ifmReqDto.getIdService());
extDao.updateRqstRespXML10g(ifmReqDto.getInterfaceReqNum(), szResponse, GGIConstants.IFM_RESPONSE);
//log.debug("CIBIL_RESPONSE_XPATH " + GGIConstants.CIBIL_RESPONSE_XPATH);
Document xmlDocument = DocumentHelper.parseText(szResponse);
String xPath = GGIConstants.RESPONSE_XPATH;
List<Node> nodes = xmlDocument.selectNodes(xPath);
for (Node node : nodes) {
String keyValue = node.valueOf(GGIConstants.RESPONSE_XPATH_KEY);
// log.debug("keyValue : " + keyValue);
if (keyValue.equalsIgnoreCase(GGIConstants.RESPONSE_XPATH_KEY_VALUE)) {
// log.debug("node value : " + node.getText());
cibilResponse = node.getText();
}
}
log.debug("cibilResponse " + cibilResponse);
String errorResponseXPATH = GGIConstants.CIBIL_ERROR_RESPONSE_XPATH;
List<Node> errorResponseNode = xmlDocument.selectNodes(errorResponseXPATH);
for (Node node : errorResponseNode) {
errorResponse = node.getText();
}
log.debug("errorResponse " + errorResponse);
if(cibilResponse!=null && cibilResponse.length()>0)
{
StringTokenizer cibilResponseResults = new StringTokenizer(cibilResponse,"**");
String tempResponse="";
ArrayList probableMatchList = new ArrayList();
while (cibilResponseResults.hasMoreElements()) {
tempResponse = (String) cibilResponseResults.nextElement();
if(tempResponse.length()>=80)
{
String memberRefNo = tempResponse.substring(69, 80).replaceAll(" ", "");
log.debug("memberRefNo " + memberRefNo);
if (memberRefNo.length() > 0) {
if (Integer.parseInt(memberRefNo) > 0) {
cibilResponse = tempResponse;
cibilResponse = cibilResponse+"**";
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
probableMatchList.add(tempResponse+"**");
}
}
else
{
cibilResponse = tempResponse+"**";
}
}
log.debug("After finding the Member reference number cibilResponse " + cibilResponse);
log.debug("After finding the Probable reference list " + probableMatchList);
// TKN 008
cibilResponse=StringEscapeUtils.unescapeXml(cibilResponse).replaceAll("[^\\x20-\\x7e]","");
ifmReqDto.setIfmTransformedResult(cibilResponse);
ifmReqDto.setProbableMatchList(probableMatchList);
}
if (errorResponse!=null && errorResponse.length()>0) {
throw new GenericInterfaceException(errorResponse
+ " for the seq_request " + ifmReqDto.getSeqRequest() + " Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.CIBIL_ERROR_CODE);
}
else if (cibilResponse==null || StringUtils.isEmpty(cibilResponse) ) {
throw new GenericInterfaceException("Cibil TUEF response is empty >> cibil Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.INTERFACE_ERROR_RESPONSE);
}
/* Setting Instinct response to ifmReqDto object */
} catch (SQLException e) {
log.error("SQLException while connecting to DataBase. Exception message is ", e);
throw new GenericInterfaceException("SQLException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.DB_OPERATION_ERROR);
} catch (GenericInterfaceException exp) {
log.error("Exception occured while valid:", exp);
throw exp;
} catch (Exception exp) {
log.error("Exception occured while valid:", exp);
throw new GenericInterfaceException("GeneralException >> Instinct Service "
+ "for the seq_request " + ifmReqDto.getSeqRequest() + "Seq_Interface_req is >> "
+ ifmReqDto.getInterfaceReqNum(),
GGIConstants.SEND_REQUEST_CONSTANT + Strings.padStart(String.valueOf(ifmReqDto.getIdService()), 2, GGIConstants.DEFAULT_NUMBER_STRING)
+ GGIConstants.UNKNOWN_ERROR);
}
return szResponse;
}
I recommend checking out the Java documentation, it provides a really good reference to start with. The .split method uses a regex to split up a string based on a delimiter.
String[] tokens = myString.split("0102\\*\\*");
For now I suspect that you forgot to escape * in split regex.
Try maybe
String[] resutl = yourString.split("0102\\*\\*");
In case you want * to represent any character then use . instead of *
String[] resutl = yourString.split("0102..");
In case you want * to represent any digit use \\d instead
String[] resutl = yourString.split("0102\\d\\d");
String string = "blabla0102**dada";
String[] parts = string.split("0102\\*\\*");
String part1 = parts[0]; // blabla
String part2 = parts[1]; // dada
Here we have a String: "blabla0102**dada", we call it string. Every String object has a method split(), using this we can split a string on anything we desire.
Do you mean literally split by "0102**"? Couldn't you use regex for that?
String[] tokens = "My text 0102** hello!".split("0102\\*\\*");
System.out.println(tokens[0]);
System.out.println(tokens[1]);
ANDROID
I am getting the below response in my WSDL API:
a:10:{s:11:"sso_user_id";s:6:"123345";s:9:"firstname";s:0:"";s:8:"lastname";s:0:"";s:5:"abono";s:0:"";s:4:"hash";s:32:"c2ff5bc4598d02160b57e2b3f28a3e0e";s:5:"token";s:32:"2da9ba3bcc52fdb047c3da5d91e3cdbd";s:5:"login";s:23:"sandor.fekete#inform.hu";s:6:"cookie";s:232:"";s:6:"access";a:1:{s:4:"role";s:2:"NO";}s:5:"error";s:0:"";}
I have taken the String between response tag,
Now here is info about the response structure:
s:11:"sso_user_id";-
sso_user_id is the key having the length of 11 character.
s:6:"123345";- 123345 is the value of sso_user_id having length of 6 character.
Now can anybody help me to PARSE or FORMAT or give REGEXP to make the normal String or easily understandable String.
NOTE:- THIS IS NOT A JSON STRING.
IOS code and logic also most welcome.
I have managed to do this:
public static void parseSOAPPrimitiveObject(String input, Object output)
throws NumberFormatException, IllegalArgumentException,
IllegalAccessException, InstantiationException {
Class theClass = output.getClass();
Field[] fields = theClass.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Type type = fields[i].getType();
fields[i].setAccessible(true);
// detect String
if (fields[i].getType().equals(String.class)) {
String tag = "" + fields[i].getName() + "";
if (input.contains(tag)) {
String strValue = "";
strValue = input.substring(input.indexOf(tag)
+ tag.length() + 2);
if (getValueLength(strValue) > 0) {
strValue = getValue(strValue);
} else {
strValue = "";
}
fields[i].set(output, strValue);
}
}
// detect int or Integer
if (type.equals(Integer.TYPE) || type.equals(Integer.class)) {
String tag = "" + fields[i].getName() + "";
if (input.contains(tag)) {
String strValue = "";
strValue = input.substring(input.indexOf(tag)
+ tag.length() + 2);
fields[i].set(output, getValueLengthInt(strValue));
}
}
}
}
public static String getValue(String substring) {
String str = new String(substring);
final Pattern pattern = Pattern.compile("\"(.+?)\"");
final Matcher matcher = pattern.matcher(str);
matcher.find();
return matcher.group(0);
}
public static int getValueLength(String substring) {
final Pattern pattern = Pattern.compile(":(.+?):");
final Matcher matcher = pattern.matcher(substring);
matcher.find();
int count = 0;
count = Integer.parseInt(matcher.group(1));
return count;
}
public static int getValueLengthInt(String substring) {
final Pattern pattern = Pattern.compile(":(.+?);");
final Matcher matcher = pattern.matcher(substring);
matcher.find();
int count = 0;
count = Integer.parseInt(matcher.group(1));
return count;
}
Class for Object:
public class SSOuser {
String sso_user_id;
String firstname;
String lastname;
String abono;
String hash;
String token;
String login;
String cookie;
String role;
String error;
}
To show Data:
SSOuser ouser = getFormatedResponseData(result.toString());
String finalValues = "";
finalValues = finalValues + "\n" + "fname= " + ouser.firstname;
finalValues = finalValues + "\n" + "lastname= " + ouser.lastname;
finalValues = finalValues + "\n" + "abono= " + ouser.abono;
finalValues = finalValues + "\n" + "hash= " + ouser.hash;
finalValues = finalValues + "\n" + "role= " + ouser.role;
finalValues = finalValues + "\n" + "sso_user_id= " + ouser.sso_user_id;
finalValues = finalValues + "\n" + "token= " + ouser.token;
finalValues = finalValues + "\n" + "login= " + ouser.login;
finalValues = finalValues + "\n" + "error= " + ouser.error;
// finalValues=finalValues+
// "\n"+"cookie= " + output.cookie;
final String val = finalValues;
runOnUiThread(new Runnable() {
public void run() {
txtValues.setText(val);}});
My task is to find the dates from resume(txt file) and calculate the duration between them
I have crated the regular expression for the duration (date) pattern like
Jan 2012 - present or Jan 2012 - Jan 2013 or 1/2013 - 2/2014 or 01/2012 - 02/2014
here are my regular expressions
private String monthPattern = "((0[1-9]|1[012]|[1-9])|(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept|Sep|Oct|Nov|Dec)[a-z]*)"; // 3 groups
private String monthAndYearSeperator="\\s*(\\s*|,|;|~|--|-|.|\\/)\\s*"; // 1 group
private String twoOrFourDigitYearPattern="(19[0-9]{2}|[2-9][0-9]{3}|[0-9]{2})\\s*"; // 1 group
private String presentPattern = "(Current|Present|Now|Currently|Presently|Till Date|Todate|Today)";
private String twoDatesSeperator = "\\s*(\\s*|-|~|--|,|to|til|till|until)\\s*"; // 1 group
private String twoOrFourDigitOrPresentYearPattern = presentPattern + "|" + twoOrFourDigitYearPattern; // 2 groups
private String secondIdenticalMonthPattern="(([1-9]|0[1-9]|1[012])|(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept|Sep|Oct|Nov|Dec|January|February|March|April|May|June|July|August|September|October|November|December))"; // 3 groups
And using the above patterns i have created one pattern for duration
private String dateToDateCompletePatternOne=
monthPattern + monthAndYearSeperator +
twoOrFourDigitYearPattern +
twoDatesSeperator + "((" + secondIdenticalMonthPattern +
monthAndYearSeperator +
twoOrFourDigitYearPattern +")|" +
presentPattern +")"
;
Now my problem is when my Resume file contains the pattern like 2013 - Jan 2014 then my regex is matching to this kind of date also but actually it should not match
please help me with this i am struggling since two weeks
please find the code below
import java.io.IOException;
import java.util.ArrayList;
import java.util.GregorianCalendar;
import java.util.HashMap;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.w3c.dom.css.Counter;
public class DatePattens {
//private ArrayList<MatchedDateObject> arryLstOfDates = new ArrayList<MatchedDateObject>();
private ArrayList<String> matchedString = new ArrayList<String>();
private HashMap<String,Integer> map ;
private String monthPattern = "((0[1-9]|1[012]|[1-9])|(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept|Sep|Oct|Nov|Dec)[a-z]*)"; // 3 groups
private String monthAndYearSeperator="\\s*(\\s*|,|;|~|--|-|.|\\/)\\s*"; // 1 group
private String twoOrFourDigitYearPattern="(19[0-9]{2}|[2-9][0-9]{3}|[0-9]{2})\\s*"; // 1 group
private String presentPattern = "(Current|Present|Now|Currently|Presently|Till Date|Todate|Today)";
private String twoDatesSeperator = "\\s*(\\s*|-|~|--|,|to|til|till|until)\\s*"; // 1 group
private String twoOrFourDigitOrPresentYearPattern = presentPattern + "|" + twoOrFourDigitYearPattern; // 2 groups
private String secondIdenticalMonthPattern="(([1-9]|0[1-9]|1[012])|(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sept|Sep|Oct|Nov|Dec|January|February|March|April|May|June|July|August|September|October|November|December))"; // 3 groups
private String dateToDateCompletePatternOne=
monthPattern + monthAndYearSeperator + twoOrFourDigitYearPattern + twoDatesSeperator +
"((" + secondIdenticalMonthPattern +
monthAndYearSeperator +
twoOrFourDigitYearPattern +")|" +
presentPattern +")"
;
private Pattern patternAry = null;
private Matcher matcher = null;
public DatePattens() {
map = new HashMap<String,Integer>();
patternAry = Pattern.compile(dateToDateCompletePatternOne, Pattern.CASE_INSENSITIVE);
matcher = patternAry.matcher("");
}
//
// extract the two dates to look for duration afterwards
// 1. check if the a year pattern exists
// 1.1 if not skip to else at the end and return false
// 2. if yes get the rest of the line past year 1
// 3. check for year 2 or CURRENT/Present/...
public boolean matchTwoYearPattern(String inputLine){
String fname="matchTwoYearPattern";
Pattern firstYearPattern = Pattern
.compile(twoOrFourDigitYearPattern,Pattern.CASE_INSENSITIVE);
Matcher matcher1 = firstYearPattern.matcher("");
Pattern secondPattern = Pattern.compile(twoOrFourDigitOrPresentYearPattern,
Pattern.CASE_INSENSITIVE);
Matcher matcher2 = secondPattern.matcher("");
//long startTime = System.currentTimeMillis();
matcher1.reset(inputLine);
if (matcher1.find()) { // 1
String remaingString = inputLine.substring(matcher1.end(),
inputLine.length()); // 2
matcher2.reset(remaingString);
if (matcher2.find()) { // 3
return true;
}
}
return false; // 1.1 and end
}
public String matchAllDatePatterns(String line, int lineNum){
String fname = "matchAllPatterns:: ";
if (matchTwoYearPattern(line) == false) { // check if two years (or year and CURRENT/today...) present, if not return false
return("false:" + line);
}
else {
}
String matched = "";
int i = 0;
matcher.reset(line);
if (matcher.find()) {
System.out.println(fname + "line: " +line);
System.out.println("group count "+matcher.groupCount());
System.out.println("group1 " +matcher.group(1));
System.out.println("group2 " +matcher.group(2));
System.out.println("group3 " +matcher.group(3));
System.out.println("group4 " +matcher.group(4));
System.out.println("group5 " +matcher.group(5));
System.out.println("group6 " +matcher.group(6));
System.out.println("group7 " +matcher.group(7));
System.out.println("group8 " +matcher.group(8));
System.out.println("group9 " +matcher.group(9));
System.out.println("group10 " +matcher.group(10));
System.out.println("group11 " +matcher.group(11));
System.out.println("group12 " +matcher.group(12));
System.out.println("group13 " +matcher.group(13));
System.out.println("group14 " + matcher.group(14));
}
return matched;
}
public static void main(String args[]){
DatePattens dp= new DatePattens();
String fileName = "Resume.txt";
try {
ReadFile file = new ReadFile(fileName);
String[] aryLines = file.openFile();
int i=0;
long startTime =System.currentTimeMillis();
for(int count=0;count<1;count++){
for (String input : aryLines) {
String output = dp.matchAllDatePatterns(input, i);
i++;
}
}
long endTime =System.currentTimeMillis();
System.out.println("Time required for this operation :" + ((endTime-startTime)*0.001));
} catch (IOException e) {
System.out.println(e);
}
}
}