Remove some text between square brackets in Java 6 - java

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);
}
}

Related

How to replace a word based on its length?

All words having the given length wordLength in the string sentence must be replaced with the word myWord. All parameters come from user input and may vary. I have tried this way but it only returns the initial string with the initial words.
Here is my source code:
package main;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) throws Exception {
String sentence = "";
int wordLength = 0;
String myWord = "";
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
System.out.println("Text input: ");
sentence = bis.readLine();
System.out.println("Word lenth to replace");
wordLength = Integer.parseInt(bis.readLine());
System.out.println("Word to replace to");
myWord = bis.readLine();
Text myText = new Text(myWord, sentence, wordLength);
myText.changeSentence();
System.out.println("New string" + myText.getSentence());
}
}
class Text {
private String mySentence;
private int charNumber;
private String wordToChange;
private String newSentence = "1.";
public Text(String wordToChange, String mySentece, int charNumber) {
this.mySentence = mySentece;
this.wordToChange = wordToChange;
this.charNumber = charNumber;
}
public String getSentence() {
return newSentence;
}
public void changeSentence() {
int firstPos = 0;
int i;
for (i = 0; i < mySentence.length(); i++) {
if (mySentence.charAt(i) == ' ') {
if (i - firstPos == charNumber) {
newSentence = newSentence.concat(wordToChange + " ");
firstPos = i + 1;
} else {
newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
firstPos = i + 1;
}
} else if (i == mySentence.length() - 1) {
if (i - firstPos == charNumber) {
newSentence = newSentence.concat(wordToChange + " ");
firstPos = i + 1;
} else {
newSentence = newSentence.concat(mySentence.substring(firstPos, i + 1));
firstPos = i + 1;
}
}
}
}
}
I changed your code a little bit:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Main {
public static void main(String[] args) {
String sentence = "";
int wordLenght = 0;
String myWord = "";
InputStreamReader is = new InputStreamReader(System.in);
BufferedReader bis = new BufferedReader(is);
try {
System.out.println("Text input: ");
sentence = bis.readLine();
System.out.println("Word lenth to replace");
wordLenght = Integer.parseInt(bis.readLine());
System.out.println("Word to replace to");
myWord = bis.readLine();
} catch (IOException e) {
e.printStackTrace();
}
Text myText = new Text(myWord, sentence, wordLenght);
System.out.println(myText.getChangeSentence());
}
}
class Text {
private String mySentence;
private int charNumber;
private String wordToChange;
private String newSentence = "1.";
public Text(String wordToChange, String mySentece, int charNumber) {
this.mySentence = mySentece;
this.wordToChange = wordToChange;
this.charNumber = charNumber;
}
public String getChangeSentence() {
String[] words = mySentence.split(" ");
for(int i = 0 ; i < words.length ; i++) {
if(words[i].length() == charNumber) {
words[i] = wordToChange;
}
}
for (String word : words) {
newSentence += word + " ";
}
return newSentence;
}
}
Input : This is a test
word length : 2
word to replace : ii
output: This ii a test
As I can see the only separator of words that is currently considered to appear in the input text is a single white space " ". If that's true, then the changeSentence method can be quite short. There is no need to do parse the sentence character by characted. Having in mind that the white space is a separator, you can simply split the sentence by the characted " " and collect them as words. After that you can just iterate through words and replace ones that lenght matches given input characters number. After that, you can just join words together with the previously used separator and that's it.
Examples if you want to try with loops
public void changeSentence() {
final String[] words = mySentence.split(" ");
for (int i = 0; i < words.length; i++) {
if (words[i].length() == charNumber) {
words[i] = wordToChange;
}
}
newSentence = String.join(" ", words);
}
or with regular expressions
public void changeSentence() {
String regex = "\\b\\w{" + charNumber+ "}\\b";
newSentence = mySentence.replaceAll(regex, wordToChange);
}
or with the stream API
public void changeSentence() {
newSentence = Arrays.stream(mySentence.split(" "))
.map(s -> s.length() == charNumber ? wordToChange : s)
.collect(Collectors.joining(" "));
}

multiple String location find using a key in a tag

I want to parse an input eg: GH123FG12B1A58 .
'GH' / 'FG' / 'A' / 'B' will be there in all the tags in same order but different position . eg: GH14555523FG1555552B55551A55558
Need to find the value after every keys
I see this can be done by using patter , get start & end index ? Is there any other way to acomplish this ?
import java.util.Scanner;
public class Shipparse {
public static void main(String[] args) {
#SuppressWarnings("resource")
Scanner Iname = new Scanner(System.in);
System.out.println("Enter the invoice :");
String Maintag = Iname.nextLine();
String GH = "GH";
String FG = "FG";
String AB = "AB";
String B = "B";
String A = "A";
int cus = Maintag.indexOf(GH);
int cys = Maintag.indexOf(FG);
int ats = Maintag.indexOf(AB);
int ss = Maintag.indexOf(B);
int se = Maintag.indexOf(A);
int tlength = Maintag.length();
StringBuilder str = new StringBuilder(Maintag);
String cnum;
if ( ats == -1) {
cnum = str.substring((cus +2) , cys);
System.out.println("Customer :" + cnum);
String cyn = str.substring((cys + 2), ss);
System.out.println("Agent :" + cyn);
} else {
cnum = str.substring((cus +2) , ats);
System.out.println("Customer :" + cnum);
String cyn = str.substring((ats + 2), ss);
System.out.println("Company:" + cyn);
}
String spoint = str.substring((ss +1) , se);
System.out.println("TYPE NUM:" + spoint);
String send = str.substring((se +1) , tlength);
System.out.println("FIELD NUM :" + send);
}
}

java.lang.ArrayIndexOutOfBoundsException :

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".

Building a string recursively in Java

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.

Split the string with new line character in gwt 2.5.1?

Following code block works fine in dev mode but when I deploy to server it does not.Could not split the multi line with new line characters?
Basically, Format the multi-line string as "," separated string tokens.
packages:
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.regexp.shared.SplitResult;
public void onSubmitComplete(SubmitCompleteEvent event) {
String plateStr = "";
if(event.getResults() != null){
String uploadStr = event.getResults();
//Log.warn(this.getClass().getName() + " - event.getResults():"+ uploadStr);
RegExp regExp = RegExp.compile("\\r?\\n");
SplitResult sp = regExp.split(uploadStr);
Log.warn(this.getClass().getName() + " - sp.length():"+ sp.length() + ", SplitResult:"+ sp.toString());
for(int i = 0; i < sp.length() ; i++){
Log.warn(this.getClass().getName() + " - PlateLine["+ i+ "] - " + sp.get(i));
if(!sp.get(i).trim().isEmpty()){
RegExp regLine = RegExp.compile(",");
SplitResult spLine = regLine.split(sp.get(i));
for(int j = 0; j < spLine.length(); j++){
if(spLine.get(j) != null && !spLine.get(j).trim().isEmpty()){
plateStr = plateStr + "," + spLine.get(j);
}
}
}
}
//plateStr = Arrays.toString(lines).replace("[","").replace("]", "");
if(!plateStr.trim().isEmpty()){
plateStr = plateStr.substring(1,plateStr.length());
}
Log.warn(this.getClass().getName() + " - PlateString:"+ plateStr);
}
I tried following workaround with java script native query but it also doesn't work.
JsArrayString arrayString = splitString(uploadStr, "\n");
public static final native JsArrayString splitString(String string, String separator) /*-{
return string.split(separator);
}-*/;
REF:
GWT JSNI split method bug

Categories

Resources