Would it be possible to change this:
[quote]user1 posted:
[quote]user2 posted:
Test1
[/quote]
Test2
[/quote]
Test3
to this:
Test3
Using Java 6?
ok, wrote some not regex solution.
String str ="[quote]user1 posted:[quote]user2 posted:Test1[/quote]Test2[/quote]Test3";
String startTag = "[quote]";
String endTag = "[/quote]";
String subStr;
int startTagIndex;
int endTagIndex;
while(str.contains(startTag) || str.contains(endTag)) {
startTagIndex = str.indexOf(startTag);
endTagIndex = str.indexOf(endTag) + endTag.length();
if(!str.contains(startTag)) {
startTagIndex = 0;
}
if(!str.contains(endTag)) {
endTagIndex = startTagIndex + startTag.length();
}
subStr = str.substring(startTagIndex, endTagIndex);;
str = str.replace(subStr, "");
}
I compiled this to Java 8. I don't believe I'm using any features not available in Java 6.
Edited: System.lineSeparator() was added in Java 1.7. I changed the line to
System.getProperty("line.separator").
public class RemoveQuotes {
public static void main(String[] args) {
String input = "[quote]user1 posted:\r\n" +
" [quote]user2 posted:\r\n" +
" Test1\r\n" +
" [/quote]\r\n" +
" Test2\r\n" +
"[/quote]\r\n" +
"Test3";
input = input.replace(System.getProperty("line.separator"), "");
String endQuote = "[/quote]";
int endPosition;
do {
int startPosition = input.indexOf("[quote]");
endPosition = input.lastIndexOf(endQuote);
if (endPosition >= 0) {
String output = input.substring(0, startPosition);
output += input.substring(endPosition + endQuote.length());
input = output;
}
} while (endPosition >= 0);
System.out.println(input);
}
}
I have a string:
2 + 2 = ${2 + 2}
This is a ${"string"}
This is an object: ${JSON.stringify({a: "B"})}
This should be "<something>": ${{
abc: "def",
cba: {
arr: [
"<something>"
]
}
}.cba.arr[0]}
This should ${"${also work}"}
And after parsing it I should get something like that:
2 + 2 = 4
This is a string
This is an object: {"a":"B"}
This should be "<something>": <something>
This should ${also work}
So I need help implementing it in Java, I simply need to get what is between ${ and }.
I tried using a regular expression: \${(.+?)} but it fails when string inside contains }
So after a bit of testing, I've ended up with this:
ScriptEngine scriptEngine = new ScriptEngineManager(null).getEngineByName("JavaScript");
String str = "2 + 2 = ${2 + 2}\n" +
"This is a ${\"string\"}\n" +
"This is an object: ${JSON.stringify({a: \"B\"})}\n" +
"This should be \"F\": ${var test = {\n" +
" a : {\n" +
" c : \"F\"\n" +
" }\n" +
"};\n" +
"test.a.c\n" +
"}\n" +
"This should ${\"${also work}\"}"; // String to be parsed
StringBuffer result = new StringBuffer();
boolean dollarSign = false;
int bracketsOpen = 0;
int beginIndex = -1;
int lastEndIndex = 0;
char[] chars = str.toCharArray();
for(int i = 0; i < chars.length; i++) { // i is for index
char c = chars[i];
if(dollarSign) {
if(c == '{') {
if(beginIndex == -1) {
beginIndex = i + 1;
}
bracketsOpen++;
} else if(c == '}') {
if(bracketsOpen > 0) {
bracketsOpen--;
}
if(bracketsOpen <= 0) {
int endIndex = i;
String evalResult = ""; // evalResult is the replacement value
try {
evalResult = scriptEngine.eval(str.substring(beginIndex, endIndex)).toString(); // Using script engine as an example; str.substring(beginIndex, endIndex) is used to get string between ${ and }
} catch (ScriptException e) {
e.printStackTrace();
}
result.append(str.substring(lastEndIndex, beginIndex - 2));
result.append(evalResult);
lastEndIndex = endIndex + 1;
dollarSign = false;
beginIndex = -1;
bracketsOpen = 0;
}
} else {
dollarSign = false;
}
} else {
if(c == '$') {
dollarSign = true;
}
}
}
result.append(str.substring(lastEndIndex));
System.out.println(result.toString());
I have a String = "abc model 123 abcd1862893007509396 abcd2862893007509404", if I provide space between abcd1 & number eg. abcd1 862893007509396 my code will work fine, but if there is no space like abcd1862893007509396, I will get java.lang.ArrayIndexOutOfBoundsException, please help ?:
PFB the code :
String text = "";
final String suppliedKeyword = "abc model 123 abcd1862893007509396 abcd2862893007509404";
String[] keywordarray = null;
String[] keywordarray2 = null;
String modelname = "";
String[] strIMEI = null;
if ( StringUtils.containsIgnoreCase( suppliedKeyword,"model")) {
keywordarray = suppliedKeyword.split("(?i)model");
if (StringUtils.containsIgnoreCase(keywordarray[1], "abcd")) {
keywordarray2 = keywordarray[1].split("(?i)abcd");
modelname = keywordarray2[0].trim();
if (keywordarray[1].trim().contains(" ")) {
strIMEI = keywordarray[1].split(" ");
for (int i = 0; i < strIMEI.length; i++) {
if (StringUtils.containsIgnoreCase(strIMEI[i],"abcd")) {
text = text + " " + strIMEI[i] + " "
+ strIMEI[i + 1];
System.out.println(text);
}
}
} else {
text = keywordarray2[1];
}
}
}
After looking at your code the only thing i can consider for cause of error is
if (StringUtils.containsIgnoreCase(strIMEI[i],"abcd")) {
text = text + " " + strIMEI[i] + " "
+ strIMEI[i + 1];
System.out.println(text);
}
You are trying to access strIMEI[i+1] which will throw an error if your last element in strIMEI contains "abcd".
I am trying to build a string recursively but it isn't quite working
my code looks like this
public void UpdatePrintList(ArrayList<Node> closedList, ArrayList<Node> openList)
{
if(count <= iterations)
{
String line1 = "";
for(int i = 0; i < closedList.size(); i++)
{
if(i > 0)
{
line1 = line1 + "-";
}
line1 = line1 + closedList.get(i).GetMovement();
}
line1 = line1 + " " + closedList.get(closedList.size()-1).GetG() + " " + closedList.get(closedList.size()-1).GetHeuristic() + " " + closedList.get(closedList.size()-1).GetF();
printList.add(line1);
//*****************************************************************
String line2 = "OPEN ";
for(int i = 0; i < openList.size(); i++)
{
line2 = FindEarlierNode(openList.get(i), line2);
}
System.out.println(line2);
}
count++;
}
private String FindEarlierNode(Node varNode, String varString)
{
if(varNode.OpenedBy() == null)
{
varString += varNode.GetMovement() + "-";
}
else
{
FindEarlierNode(varNode.OpenedBy(), varString);
}
varString = varString + varNode.GetMovement() + "-";
return varString;
}
The strange thing is that I know that this if statement
if(varNode.OpenedBy() == null)
{
varString += varNode.GetMovement() + "-";
}
runs correctly, so the function does reach the earliest node. But it doesnt add to the string. The code runs but returns nothing. GetMovement just returns a one or two character string. The output should look like this:
OPEN S-R S-RD S-D
But instead it looks like this:
OPEN D-DL-L-
Can anyone help?
Managed to work it out. This gives me my desired output:
private String FindEarlierNode(Node varNode, String varString)
{
if(varNode.OpenedBy() != null)
{
varString = varString + varNode.GetMovement() + "-";
return FindEarlierNode(varNode.OpenedBy(), varString);
}
return varString += varNode.GetMovement() + " ";
}
thanks everyone.
LINE READING RULES:
no indent/dash == major disease
one indent/dash(-) == subIndent1
two indent/dash(--)== subIndent2
three indent/dash(---)== subIndent3
four indent/dash(----)== subIndent4
five indent/dash(-----)== subIndent5
six indent/dash(-----)== subIndent6
Disease.txt(original short sample)
http://www.cdc.gov/nchs/data/dvs/2e_volume3_2014.pdf (full Disease ICD file sample)
Aars Q87.1
Abdomen, abdominal — see also condition
- acute R10.0
-- convulsive
equivalent G40.8
Abdominalgia R10.4
Abduction contracture, hip or other joint —see Contraction, joint
Aberrant (congenital) — see also Malposition, congenital
- adrenal gland Q89.1
- artery (peripheral) NEC Q27.8
- breast Q83.8
Aberration, mental F99.0
- endocrine gland NEC Q89.2
- hepatic duct Q44.5
- pancreas Q45.3
-- vein (peripheral)
pender NEC Q27.8
I have tried following code. All Above rules are working fine on reading line by line Disease text file.
Bean for major disease: DiseaseCategory.java
public class DiseaseCategory {
private int mdId;
private String mdName;
private String mdCode;
DiseaseCategory(int mdId, String mdName, String mdCode){
this.mdId=mdId;
this.mdName=mdName;
this.mdCode=mdCode;
//setter and getters below
}
Bean for sub indent disease: SubDiseaseCategory .java
public class SubDiseaseCategory {
SubDiseaseCategory(int sdId, int mdId, String sdIndent1,String sdCode1,
String sdIndent2, String sdCode2, String sdIndent3,String sdCode3,String sdIndent4,String sdCode4,
String sdIndent5,String sdCode5,String sdIndent6, String sdCode6)
{
this.sdId=sdId;
this.mdId=mdId;
this.sdIndent1=sdIndent1;
this.sdCode1=sdCode1;
this.sdIndent2=sdIndent2;
this.sdCode2=sdCode2;
this.sdIndent3=sdIndent3;
this.sdCode3=sdCode3;
this.sdIndent4=sdIndent4;
this.sdCode4=sdCode4;
this.sdIndent5=sdIndent5;
this.sdCode5=sdCode5;
this.sdIndent6=sdIndent6;
this.sdCode6=sdCode6;
}
private int sdId;
private int mdId;
private String sdIndent1;
private String sdCode1 ;
private String sdIndent2;
private String sdCode2 ;
private String sdIndent3;
private String sdCode3 ;
private String sdIndent4;
private String sdCode4 ;
private String sdIndent5;
private String sdCode5 ;
private String sdIndent6;
private String sdCode6 ;
//all setters and getters
}
Main function performing in DataMigeration.java
public class DataMigeration
{
public static void main(String args[]) throws IOException
{
String FILE_NAME="c://com/best/uibeans/diseases.txt";
File file=new File(FILE_NAME);
DataMigeration ob=new DataMigeration();
//ob.connection();
ob.readAndSaveFile(file);
}
private Connection conn=null;
private Statement stmt=null;
public void connection() {
String userName = "guest";
String password = "";
String url="jdbc:sqlserver://JAVASERVER2\\MTS;databaseName=ICD";
try {
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
System.out.println("Driver Loaded.........");
} catch (ClassNotFoundException e) {
System.out.println("Driver not Loaded..........");
e.printStackTrace();
}
try {
conn = DriverManager.getConnection(url, userName, password);
System.out.println("Connection Established..........");
stmt=conn.createStatement();
} catch (SQLException e) {
e.printStackTrace();
System.out.println("Connection not Established..........");
}
}
public void SaveMajorDisease(int mdId, String mdName, String mdCode){
try {
String query="";
mdName= mdName.replace("'", "");
mdName=mdName.trim();
query="insert into MAJOR_DISEASE(md_id, md_name, md_code) " +
"values ("+mdId+",'"+mdName+"','"+mdCode+"')";
c(query);
stmt.executeUpdate(query);
System.out.println("Data Inserted Succesfully....");
} catch (SQLException e) {
System.out.println("Data Not Inserted Succesfully....");
e.printStackTrace();
}
}
public void SaveSubDisease(
int sdId, int mdId,
String sdIndent1, String sdCode1,
String sdIndent2, String sdCode2,
String sdIndent3, String sdCode3,
String sdIndent4, String sdCode4,
String sdIndent5, String sdCode5,
String sdIndent6, String sdCode6
){
try {
String query="";
sdIndent1= sdIndent1.replace("'", "");
sdIndent1=sdIndent1.trim();
sdIndent2= sdIndent2.replace("'", "");
sdIndent2=sdIndent2.trim();
sdIndent3= sdIndent3.replace("'", "");
sdIndent3=sdIndent3.trim();
sdIndent4= sdIndent4.replace("'", "");
sdIndent4=sdIndent4.trim();
sdIndent5= sdIndent5.replace("'", "");
sdIndent5=sdIndent5.trim();
sdIndent6= sdIndent6.replace("'", "");
sdIndent6=sdIndent6.trim();
query="insert into SUB_DISEASE(sd_id, md_id, " +
" sd_indent1, sd_code1 , " +
" sd_indent2, sd_code2 , " +
" sd_indent3, sd_code3 , " +
" sd_indent4, sd_code4 , " +
" sd_indent5, sd_code5 , " +
" sd_indent6, sd_code6 " +
" ) " +
"values ("+sdId+","+mdId+", " +
" '"+sdIndent1+"' , '"+sdCode1+"' , " +
"'"+sdIndent2+"' , '"+sdCode2+"' ," +
"'"+sdIndent3+"' , '"+sdCode3+"' ," +
"'"+sdIndent4+"' , '"+sdCode4+"' ," +
"'"+sdIndent5+"' , '"+sdCode5+"' ," +
"'"+sdIndent6+"' , '"+sdCode6+"' " +
" ) ";
c(query);
stmt.executeUpdate(query);
System.out.println("Data Inserted Succesfully....");
} catch (SQLException e) {
System.out.println("Data Not Inserted Succesfully....");
e.printStackTrace();
}
}
public void readAndSaveFile(File file)
{
List<DiseaseCategory> majorDiseaseList=new ArrayList<DiseaseCategory>();
List<SubDiseaseCategory> subDiseaseList=new ArrayList<SubDiseaseCategory>();
try
{
String data="";
String line;
BufferedReader br = new BufferedReader(new FileReader(file));
String majorDiseaseCode="";
String majorDisease="";
String sdIndent1="";
String sdCode1="" ;
String sdIndent2="";
String sdCode2="" ;
String sdIndent3="";
String sdCode3="" ;
String sdIndent4="";
String sdCode4="" ;
String sdIndent5="";
String sdCode5="" ;
String sdIndent6="";
String sdCode6="" ;
// _________________________________________________________//
/* major disease record: majorDiseaseList */
int mdId=0;
int sdId=0;
while ((line = br.readLine()) != null)
{
majorDisease="";
majorDiseaseCode="";
if(!line.equals("")){
if(lineContainsNoIndentAtFirst(line)==0)
{
String tokens[]=line.split(" ");
for(int i=0;i<tokens.length;i++)
{
if(tokens[i].contains(".")) if(tokens[i]!="0") majorDiseaseCode=tokens[i];
if(!tokens[i].contains(".")) if(tokens[i]!="0") majorDisease+=" "+tokens[i];
}
if(!majorDisease.equals(null) && !majorDisease.equals("") && majorDisease!="" && majorDisease!=null){
mdId++;
majorDiseaseList.add(new DiseaseCategory(mdId, majorDisease, majorDiseaseCode));
}
}//end if
else if(lineContainsNoIndentAtFirst(line)!=0)// for no dash or no any suffix at beginning
{
sdId++;
if(lineContainsOneIndentAtFirst(line)==0) // for one '-' only
{
String tokens1[]=line.split(" ");
sdIndent1="";
for(int i=0;i<tokens1.length;i++)
{
if(tokens1[i].contains(".")) if(tokens1[i]!="0") sdCode1=tokens1[i];
if(!tokens1[i].contains(".")) if(tokens1[i]!="0") sdIndent1+=" "+tokens1[i];
sdIndent1= sdIndent1.replace("-", "");
}
subDiseaseList.add(new SubDiseaseCategory(
sdId,
mdId,
sdIndent1,
sdCode1,"","","","","","","","","",""
));
}//end if: lineContainsOneIndentAtFirst()
else if(lineContainsTwoIndentAtFirst(line)==0) // for two '--' only
{
String tokens2[]=line.split(" ");
sdIndent2="";
for(int i=0;i<tokens2.length;i++)
{
if(tokens2[i].contains(".")) if(tokens2[i]!="0") sdCode2=tokens2[i];
if(!tokens2[i].contains(".")) if(tokens2[i]!="0") sdIndent2+=" "+tokens2[i];
sdIndent2= sdIndent2.replace("-", "");
}
subDiseaseList.add(new SubDiseaseCategory(
sdId,
mdId,"","",
sdIndent2,
sdCode2,"","","","","", "", "", ""
));
}//end if: lineContainsTwoIndentAtFirst()
else if(lineContainsThreeIndentAtFirst(line)==0) // for three '---' only
{
String tokens3[]=line.split(" ");
sdIndent3="";
for(int i=0;i<tokens3.length;i++)
{
if(tokens3[i].contains(".")) if(tokens3[i]!="0") sdCode3=tokens3[i];
if(!tokens3[i].contains(".")) if(tokens3[i]!="0") sdIndent3+=" "+tokens3[i];
sdIndent3= sdIndent3.replace("-", "");
}
subDiseaseList.add(new SubDiseaseCategory(
sdId,
mdId,"","","","",
sdIndent3,
sdCode3,"","","", "", "", ""
));
}//end if: lineContainsThreeIndentAtFirst()
else if(lineContainsFourIndentAtFirst(line)==0) // for Four '----' only
{
String tokens4[]=line.split(" ");
sdIndent4="";
for(int i=0;i<tokens4.length;i++)
{
if(tokens4[i].contains(".")) if(tokens4[i]!="0") sdCode4=tokens4[i];
if(!tokens4[i].contains(".")) if(tokens4[i]!="0") sdIndent4+=" "+tokens4[i];
sdIndent4= sdIndent4.replace("-", "");
}
subDiseaseList.add(new SubDiseaseCategory(
sdId,
mdId,"","","","","","",
sdIndent4,
sdCode4,"", "", "", ""
));
}//end if: lineContainsFourIndentAtFirst()
else if(lineContainsFiveIndentAtFirst(line)==0) // for Four '----' only
{
String tokens5[]=line.split(" ");
sdIndent5="";
for(int i=0;i<tokens5.length;i++)
{
if(tokens5[i].contains(".")) if(tokens5[i]!="0") sdCode5=tokens5[i];
if(!tokens5[i].contains(".")) if(tokens5[i]!="0") sdIndent5+=" "+tokens5[i];
sdIndent5= sdIndent5.replace("-", "");
}
subDiseaseList.add(new SubDiseaseCategory(
sdId,
mdId,"","","","","","","","",
sdIndent5,
sdCode5, "", ""
));
}//end if: lineContainsFiveIndentAtFirst()
else if(lineContainsSixIndentAtFirst(line)==0) // for Four '----' only
{
String tokens6[]=line.split(" ");
for(int i=0;i<tokens6.length;i++)
{
if(tokens6[i].contains(".")) if(tokens6[i]!="0") sdCode6=tokens6[i];
if(!tokens6[i].contains(".")) if(tokens6[i]!="0") sdIndent6+=" "+tokens6[i];
sdIndent6= sdIndent6.replace("-", "");
}
subDiseaseList.add(new SubDiseaseCategory(
sdId,
mdId,"","","","","","","","","","",
sdIndent6,
sdCode6
));
}//end if: 5indent
}//end if: suffix: '-'
}//if for not null index
}// end while loop for line by line reading from text
//Retrieving.....
int maxRecords=1;
int masterMax=1;
for(DiseaseCategory obj: majorDiseaseList){
masterMax++;
// System.out.print("\n"+obj.getMdId()+" : "+obj.getMdName()+" : "+obj.getMdCode());
//saving Major disease
String mdName=obj.getMdName();
// String tokensEscape[]=mdName.split("\'");
// for(int i=0;i<tokensEscape.length;i++) mdName+="\'"+tokensEscape[i];
//
// System.out.print("\n"+obj.getMdId()+" : "+mdName+" : "+obj.getMdCode());
//
SaveMajorDisease(obj.getMdId(),mdName,obj.getMdCode());
}
System.out.println("\n____size:"+subDiseaseList.size()+"_________________________________________________________________________________________________________________________________\n");
for(SubDiseaseCategory obj: subDiseaseList){
maxRecords++;
String msg="";
msg+= obj.getSdId()+" : "+obj.getMdId();
if(!obj.getSdIndent1().equals("")) msg+= ": i: "+obj.getSdIndent1()+" : \t\t\tcode1: "+obj.getSdCode1();
if(!obj.getSdIndent2().equals("")) msg+= ": ii: "+obj.getSdIndent2()+" : \t\t\tcode2: "+obj.getSdCode2();
if(!obj.getSdIndent3().equals("")) msg+= ": iii: "+obj.getSdIndent3()+" : \t\t\tcode3: "+obj.getSdCode3();
if(!obj.getSdIndent4().equals("")) msg+= ": iv: "+obj.getSdIndent4()+" : \t\t\tcode4: "+obj.getSdCode4();
if(!obj.getSdIndent5().equals("")) msg+= ": v: "+obj.getSdIndent5()+" : \t\t\tcode5: "+obj.getSdCode5();
if(!obj.getSdIndent6().equals("")) msg+= ": vi: "+obj.getSdIndent6()+" : \t\t\tcode6: "+obj.getSdCode6();
// System.out.println(msg);
//saving sub_disease
SaveSubDisease(
obj.getSdId(), obj.getMdId(),
obj.getSdIndent1(), obj.getSdCode1(),
obj.getSdIndent2(), obj.getSdCode2(),
obj.getSdIndent3(), obj.getSdCode3(),
obj.getSdIndent4(), obj.getSdCode4(),
obj.getSdIndent5(), obj.getSdCode5(),
obj.getSdIndent6(), obj.getSdCode6()
);
}
br.close();
}
catch(IOException ioe){}
}
public int lineContainsNoIndentAtFirst(String str)
{
int contains=0;
// if(!str.startsWith("-"))
// {
String dashCheck = str.substring(0,1)+"";
if( dashCheck.contains("-")) contains++;
if(!dashCheck.contains("-")) contains=0;
// String tokensDotCheck[]=str.split(" ");
// for(int i=0;i<tokensDotCheck.length;i++)
// {
// if(i==0){
// if(tokensDotCheck[i].contains(".")){
// contains++;
// }
// }
// }
//
// }else{
// contains++;
// }
return contains;
}
public int lineContainsOneIndentAtFirst(String str)
{
String dashCheck = str.substring(0,3)+"";
int contains=0;
if(dashCheck.contains("- -")) contains++;
return contains;
}
public int lineContainsTwoIndentAtFirst(String str){
String dashCheck = str.substring(0,6)+"";
int contains=0;
if(dashCheck.contains("- - - ")) contains++;
return contains;
}
public int lineContainsThreeIndentAtFirst(String str){
String dashCheck = str.substring(0,8)+"";
int contains=0;
if(dashCheck.contains("- - - - ")) contains++;
return contains;
}
public int lineContainsFourIndentAtFirst(String str){
String dashCheck = str.substring(0,10)+"";
int contains=0;
if(dashCheck.contains("- - - - - ")) contains++;
return contains;
}
public int lineContainsFiveIndentAtFirst(String str){
String dashCheck = str.substring(0,12)+"";
int contains=0;
if(dashCheck.contains("- - - - - - ")) contains++;
return contains;
}
public int lineContainsSixIndentAtFirst(String str){
String dashCheck = str.substring(0,14)+"";
int contains=0;
if(dashCheck.contains("- - - - - - ")) contains++;
return contains;
}
public void c(String msg){ System.out.print("\n| "+msg);}
}
above code is working fine on rules but problem is below,
Problem:
Abdomen, abdominal — see also condition
- acute R10.0
-- convulsive
equivalent G40.8
wrapped sub disease indent is counting on Rule 1 that no indent/dash is equals to major disease but it that is wrapped text of above line.it should not be counted in major disease but it should be counted in previous sub disease indent line.
how to solve this conflict?
possibly i have shared all things if any one have any difficulty in giving answer you can ask through comment.I will tell you.