I am getting following values in my String variable:
យោងតាមឯកឧត្តមតាំង សាមឿនលេខាសម្តេចកិត្តិព្រឹទ្ធបណ្ឌិតប៊ុន រ៉ានីហ៊ុនសែនបានប្រាប់ក្រុមអ្នក\r\nសារព័ត៌មានថា៖ក្នុងជំនួបសម្តែងការគួរសមនិងទទួលថវិការ៦រយដុល្លាអាមេរិក និងសម្ភារៈឧបករណ៍\r\nព្រមទាំងបរិក្ខារពេទ្យ មួយចំនួនពីក្រុមយុវជនកម្ពុជាជូនលោកជំទាវ អាន្នីសុខអានអនុប្រធានតំណាង\r\nដ៏ខ្ពង់ខ្ពស់សម្តេចកិត្តិព្រឹទ្ធបណ្ឌិតប៊ុន រ៉ានីហ៊ុន សែនប្រធានកាកបាទក្រហមកម្ពុជានៅទីស្នាក់ការកណ្តាល\r\nកាកបាទក្រហមកម្ពុជាអូរបែកក្អមក្នុងរាជធានីភ្នំពេញនាថ្ងៃទី២ខែកញ្ញាឆ្នាំ២០១៤។\r\n\r\nលោកជំទាវអាន្នីសុខ អានបានកោតសសើរចំពោះក្រុមយុវជនកម្ពុជាដែលបានយកថវិកានិងសម្ភារៈមកជូន\r\nកាកបាទក្រហមកម្ពុជាសកម្មភាពនេះបង្ហាញពីអោយឃើញពីបេះដូងមនុស្សធម៌នៃវប្បធម៌ចែ
in which i have \r\n with different sequence
for example:
\r\n
\r\n\r\n
\r\n\r\n\r\n\r\n
i have used following all functions none of them works, any one guide me what mistake am i doing?
private List<ContentValues> parseJsonBreakingNews(String json) throws JSONException {
List<ContentValues> result = new ArrayList<ContentValues>();
JSONArray allItems = new JSONArray(json);
JSONObject item;
for (int i = 0; i < allItems.length(); i++) {
item = allItems.getJSONObject(i);
ContentValues values = new ContentValues();
values.put(TableBreakingNews._ID, item.getInt("id"));
String x = item.getString("title_kh");
String y = item.getString("content_kh");
String title = RemoveSpecialCharacters(x);
String description = RemoveSpecialCharacters(y);
values.put(TableBreakingNews.TITLE_KH, title);
values.put(TableBreakingNews.CONTENT_KH,description);
values.put(TableBreakingNews.DATE, item.getString("dt"));
result.add(values);
}
return result;
}
private String RemoveSpecialCharacters(String JunkData)
{
JunkData = JunkData.replaceAll("\\r", "");
JunkData = JunkData.replaceAll("\\n", "");
//JunkData = JunkData.replaceAll("[\n\r]+", " ");
//JunkData = JunkData.replaceAll("[\r\n]+", " ");
//JunkData = JunkData.replaceAll("\\r", "2222222222222");
//JunkData = JunkData.replaceAll("\\n", "111111111111");
//JunkData = JunkData.replaceAll("\\r\\n", "0000000000000000");
// String newLine = System.getProperty("line.separator");
//JunkData = JunkData.replace(newLine, "");
//JunkData = JunkData.replace('\n', '');
//JunkData = RemoveLineTerminationCharacters(JunkData);
//JunkData = RemoveLineTabs(JunkData);
return JunkData;
}
any help would be appreciated.
I can't see the whole code, but i think your problem is the reference from this String, have a look at my test:
Maybe you are calling your method but not updating your real reference of the object.
I don't know exactly what is your problem. if you could, please explain better what you want.
--- Edited ----
Try your method this way:
private String removeSpecialCharacters(String junkData) {
junkData = junkData.replaceAll("(\r\n|\n)", "");
return junkData;
}
Try
replace("\n", "");
or
private static final String newLine = System.getProperty("line.separator");
replace(newline, "");
Something like that should work for you
Related
I posted a question in the past but didn't get any response so I'm assuming my question wasn't clear.
Can we define new Object[3][] without defining number of columns?
Hoping following code is more readable and easy to understand.
Question:
Why is retval[0] always null?
Please help.
Thanks,
package YTesting1.YTesting1;
import org.testng.annotations.Test;
public class Test1 {
#Test
public void MyTest() {
Object[][] retval = new Object[1][];
String mm = "Hello";
String o = "World";
String s = "Yeaah";
(new Object[1])[0] = new Test2(mm, o, s);
retval[0] = new Object[1];
System.out.println("retval = " +retval[0]);
}
}
package YTesting1.YTesting1;
public class Test2 {
private String str1 = "";
private String str2 = "";
private String str3= "";
public Test2(String lstr1, String lstr2, String lstr3){
this.str1 = lstr1;
this.str2 = lstr2;
this.str3 = lstr3;
}
}
retval[0] is not null, it is assigned to an empty array of Object.
It is possible to assign to retval[0] some another array and populate it without indicating the number of columns
public static void main(String ... args) {
Object[][] retval = new Object[1][];
String mm = "Hello";
String o = "World";
String s = "Yeaah";
//(new Object[1])[0] = new Test2(mm, o, s);
retval[0] = new Object[1];
System.out.println("retval[0] = " + retval[0]);
System.out.println("retval[0][0] = " +retval[0][0]);
System.out.println("retval = " + Arrays.deepToString(retval));
retval[0] = new String[] { // 3-element string array
mm, o, s
};
System.out.println("retval[0] = " + retval[0]);
System.out.println("retval[0][0] = " +retval[0][0]);
System.out.println("retval = " + Arrays.deepToString(retval));
}
Output:
retval[0] = [Ljava.lang.Object;#5479e3f
retval[0][0] = null
retval = [[null]]
retval[0] = [Ljava.lang.String;#66133adc
retval[0][0] = Hello
retval = [[Hello, World, Yeaah]]
Get different parts of two similar strings
example:
1.String1="bjsqzctjjzxyxgs" String2="bjqzctjjxxzxyxgs" result:String[] s3 = {"s","xx"}
2.String1="bjssdwxxjsyxgs" String2="bjsdwxxjsyxgs" result:String[] s3 = {"s"}
3.String1="bjydcrwljskjyxgs" String2="bjydcrjswlkjyxgs" result:String[] s3 = {"wljs","jswl"}
for the example1,i make the string to the char array ,then i can get the String "sqzctjj" and "qzctjjxx",but i cant get the result like the example result {"s","xx"}.
I hope some friends can guide me out.
thanks
public static Map<String,String> getPreviousStrAndLastStr(String shortCompanyName, String shortSelectCompanyName){
char[] shortCompanyNameCharArray = (shortCompanyName).toCharArray();
char[] shortSelectCompanyNameCharArray = shortSelectCompanyName.toCharArray();
Map<String,String> map = new HashMap<String,String>();
int cirNum = 0;
int previousDifIndex = 0;
int lastDifIndex = 0;
String longSplitStr = "";
String shortSplitStr = "";
if(shortCompanyNameCharArray.length>shortSelectCompanyNameCharArray.length){
cirNum = shortSelectCompanyNameCharArray.length;
longSplitStr = shortCompanyName;
shortSplitStr = shortSelectCompanyName;
}else{
cirNum = shortCompanyNameCharArray.length;
longSplitStr = shortSelectCompanyName;
shortSplitStr = shortCompanyName;
}
for(int i=0;i<cirNum;i++){
if (shortCompanyNameCharArray[i]!=shortSelectCompanyNameCharArray[i]){
System.out.println(shortCompanyNameCharArray[i]+"--------"+shortSelectCompanyNameCharArray[i]);
previousDifIndex = i;
break;
}
}
if(previousDifIndex != 0){
for(int i=0;i<cirNum;i++){
if (shortCompanyNameCharArray[shortCompanyNameCharArray.length-i-1]!=shortSelectCompanyNameCharArray[shortSelectCompanyNameCharArray.length-i-1]){
System.out.println(shortCompanyNameCharArray[shortCompanyNameCharArray.length-i-1]+"--------"+shortSelectCompanyNameCharArray[shortSelectCompanyNameCharArray.length-i-1]);
lastDifIndex =shortSplitStr.length() - i;
break;
}
if(previousDifIndex==(cirNum-i)){
lastDifIndex = shortSplitStr.length() - i;;
break;
}
}
}
String previousStr = shortSplitStr.substring(0,previousDifIndex);
String lastStr = shortSplitStr.substring(lastDifIndex,shortSplitStr.length());
String diffStr1 = longSplitStr.replace(previousStr,"").replace(lastStr,"");
String diffStr2 = shortSplitStr.replace(previousStr,"").replace(lastStr,"");
map.put("previousStr",previousStr);
map.put("lastStr",lastStr);
map.put("diffStr1",diffStr1);
map.put("diffStr2",diffStr2);
map.put("previousDifIndex",previousDifIndex+"");
map.put("lastDifIndex",lastDifIndex+"");
return map;
}
input "bjydcrwljskjyxgs" and "bjqzctjjxxzxyxgs"
output {diffStr2=sqzctjj, previousStr=bj, diffStr1=qzctjjxx, lastDifIndex=9, lastStr=zxyxgs, previousDifIndex=2}
so i want to make the diffStr1="qzctjjxx"and the diffStr2="sqzctjj" how to be
the String[] s3 = {"s","xx"}
public class TagHandler {
private final String START = "<START ";
private final String END = "<END ";
public String handleTag(String buf, String[] attrList) {
String startPattern1 = START+attrList[0]+">";
String endPattern1 = END+attrList[0]+">";
String startPattern2 = START+attrList[1]+">";
String endPattern2 = END+attrList[1]+">";
String startPattern3 = START+attrList[2]+">";
String endPattern3 = END+attrList[2]+">";
String startPattern4 = START+attrList[3]+">";
String endPattern4 = END+attrList[3]+">";
String startPattern5 = START+attrList[4]+">";
String endPattern5 = END+attrList[4]+">";
String extract1 = new String(buf);
String extract2 = new String(buf);
String extract3 = new String(buf);
String extract4 = new String(buf);
String extract5 = new String(buf);
extract1 = extract1.substring(extract1.indexOf(startPattern1)+startPattern1.length(), extract1.indexOf(endPattern1));
extract2 = extract2.substring(extract2.indexOf(startPattern2)+startPattern2.length(), extract2.indexOf(endPattern2));
extract3 = extract3.substring(extract3.indexOf(startPattern3)+startPattern3.length(), extract3.indexOf(endPattern3));
extract4 = extract4.substring(extract4.indexOf(startPattern4)+startPattern4.length(), extract4.indexOf(endPattern4));
extract5 = extract5.substring(extract5.indexOf(startPattern5)+startPattern5.length(), extract5.indexOf(endPattern5));
String s = ("BLOPABP"+extract1) + ("\nBLOPCALL"+extract2) +("\nBLOPEXP"+extract3) +("\nBLOPHEAD"+extract4)+("\nBLOPMAJ"+extract5);
return s;
}
How would I tidy up the code above into some sort of loop? Basically I have a file that i'm reading and extract the data within the tags and I'm passing the tags into this TagHandler method and returning the extracted data as a string with the tag headers without the "< START >" and "< END TAG"> leaving only the header on the start tag.
Here you go. This should do what you want.
public class TagHandler {
private final String START = "<START ";
private final String END = "<END ";
public String handleTag(String buf, String[] attrList) {
String[] blop = {"BLOPABP", "BLOPCALL", "BLOPEXP", "BLOPHEAD", "BLOPMAJ"};
String s = "";
for (int i = 0; i < attrList.length; i++) {
String startPattern = START+attrList[i]+">";
String endPattern = END+attrList[i]+">";
String extract = buf.substring(buf.indexOf(startPattern)+startPattern.length(), buf.indexOf(endPattern));
s += blop[i]+extract;
if (i < attrList.length-1) {
s += "\n";
}
}
return s;
}
}
Look out for an out of bounds exception, if attrList has more than 5 elements.
You can try something like this, optimize it if you can :
public String handleTag(String buf, String[] attrList) {
StringBuilder temp = new StringBuilder();
final String[] prefix = {"BLOPABP","\nBLOPCALL","\nBLOPEXP",
"\nBLOPHEAD","\nBLOPMAJ"};
for(int i=0;i<attrList.length;i++){
String startPattern = START+attrList[i]+">";
String endPattern = END+attrList[i]+">";
String extract = new String(buf);
extract = extract.substring(
extract.indexOf(startPattern)+startPattern.length(),
extract.indexOf(endPattern));
temp.append(prefix[i%5]+extract);
}
return temp.toString();
}
This should work. You can replace = new ArrayList<String> with = new ArrayList<>() if you're using java 7.
private final String START = "<START ";
private final String END = "<END ";
List<String> startPatterns = new ArrayList<String>();//can use ArrayList<> instead if java 1.7
List<String> stringExtracts = new ArrayList<String>();
final String[] tags = new String[]{"BLOPABP","\nBLOPCALL","\nBLOPEXP","\nBLOPHEAD","\nBLOPMAJ"};
public String handleTag(String buf, String[] attrList) {
int numPatterns = tags.length;
String s;
String extract = new String(buf);
for(int i=0; i<numPatterns; i++){
String startPattern = START+attrList[i]+">";
startPatterns.add(startPattern);
String endPattern = END+attrList[i]+">";
endPatterns.add(endPattern);
String extract = extract.substring(extract.indexOf(startPattern)+startPattern.length(), extract.indexOf(endPattern));
stringExtracts.add(extract);
s += tags[i] + extract;
}
return s;
}
This assumes that you need access to the individual startPatterns, endPatterns and stringExtracts again, not just s. If you only need s though then discard the ArrayLists - it will work like this:
private final String START = "<START ";
private final String END = "<END ";
final String[] tags = new String[]{"BLOPABP","\nBLOPCALL","\nBLOPEXP","\nBLOPHEAD","\nBLOPMAJ"};
public String handleTag(String buf, String[] attrList) {
int numPatterns = tags.length;
String s;
String extract = new String(buf);
for(int i=0; i<numPatterns; i++){
String startPattern = START+attrList[i]+">";
String endPattern = END+attrList[i]+">";
String extract = extract.substring(extract.indexOf(startPattern)+startPattern.length(), extract.indexOf(endPattern));
s += tags[i] + extract;
}
return s;
}
public class Readparam
{
private static String method_name;
public static HashMap<String, Vector<String>> getParameters(String file_name)
{
HashMap temp_map = new HashMap();
String current_dir = System.getProperty("user.dir");
File new_file = new File(current_dir + "\\parameters\\" + file_name);
StringTokenizer stringtok = null;
StringBuffer temp_contents = new StringBuffer();
BufferedReader input = null;
try
{
input = new BufferedReader(new FileReader(new_file));
String current_line = null;
while (((current_line = input.readLine()) != null) && (current_line.length() > 0))
{
stringtok = new StringTokenizer(current_line, "(");
method_name = stringtok.nextToken();
String parsed_parameters = current_line.subSequence(current_line.indexOf("(") + 1, current_line.indexOf(")")).toString();
StringTokenizer paramtok = new StringTokenizer(parsed_parameters, ",");
String[] parsed_string = parsed_parameters.split(", ");
String parsing = method_name + "(";
for (int i = 0; i < parsed_string.length; i++)
{
String[] temp_parse = parsed_string[i].split(" ");
if (i < parsed_string.length - 1)
parsing = parsing + temp_parse[0] + ", ";
else {
parsing = parsing + temp_parse[0];
}
}
parsing = parsing + ")";
Vector temp_vector = new Vector();
for (String s : parsed_string) {
temp_vector.add(s);
}
temp_map.put(parsing, temp_vector);
}
}
catch (FileNotFoundException ex)
{
System.out.println("File not found: " + file_name);
String method_name = null;
return method_name;
}
any help on this is aprreciated
I have the last line "return method_name that does not compile
i recieve an error incompatible types, expected java.util.hashmap found java.lang.String
the last line return method_name does not compile
System.out.println("File not found: " + file_name);
HashMap<String, Vector<String>> method_name = null;
return method_name;
Since your method is of a certain type, you need to 'cast' the value that's being returned to that type.
If you are coding using Eclipse, you can just click on the little error icon, and it will offer to fix the error for you, and it will cast it for you. If you are not using Eclipse, you might consider it in the future. (NetBeans works in a similar manner)
Your method is declared to return HashMap<String, Vector<String>> (which is odd to start with - usually you'd use List rather than Vector if you're using the Java 2 collections). But then your only return statement is here:
String method_name = null;
return method_name;
That's clearly not returning a HashMap<String, Vector<String>>, is it? What do you expect that to do? You could just write
return null;
which would return a null reference as a HashMap<String, Vector<String>>. (Personally I'd just let the exception bubble up, but that's a different matter.)
(It also doesn't help that you haven't shown the end of your method, and that some of the indentation is decidedly odd.)
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = reg.exec(text);
for (int i = 0; i < matchResult.getGroupCount(); i++) {
System.out.println("group" + i + "=" + matchResult.getGroup(i));
}
I am trying to get all blocks which are encapsulated by squared bracets form a path string:
and I only get group0="[build]" what i want is:
1:"[build]" 2:"[something]" 3:"[build]"
EDIT:
just to be clear words inside the brackets are generated with random text
public static String genText()
{
final int LENGTH = (int)(Math.random()*12)+4;
StringBuffer sb = new StringBuffer();
for (int x = 0; x < LENGTH; x++)
{
sb.append((char)((int)(Math.random() * 26) + 97));
}
String str = sb.toString();
str = str.substring(0,1).toUpperCase() + str.substring(1);
return str;
}
EDIT 2:
JDK works fine, GWT RegExp gives this problem
SOLVED:
Answer from Didier L
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String result = "";
String text = "[build]/directory/[something]/[build]/";
RegExp reg = RegExp.compile(linkPattern,"g");
MatchResult matchResult = null;
while((matchResult=reg.exec(text)) != null){
if(matchResult.getGroupCount()==1)
System.out.println( matchResult.getGroup(0));
}
I don't know which regex library you are using but using the one from the JDK it would go along the lines of
String linkPattern = "\\[[A-Za-z_0-9]+\\]";
String text = "[build]/directory/[something]/[build]/";
Pattern pat = Pattern.compile(linkPattern);
Matcher mat = pat.matcher(text);
while (mat.find()) {
System.out.println(mat.group());
}
Output:
[build]
[something]
[build]
Try:
String linkPattern = "(\\[[A-Za-z_0-9]+\\])*";
EDIT:
Second try:
String linkPattern = "\\[(\\w+)\\]+"
Third try, see http://rubular.com/r/eyAQ3Vg68N