How to get a multiple substrings from a string - java

I have a string that might look like this:
searchText = search:kind:(reports) unit.id:(("CATS (WILLIAMS)"~1) OR ("DOGS (JAMES)"~1))
I need to extact any values that may exist in the quotation marks so in this case it would be:
CATS (WILLIAMS) and DOGS (JAMES)
Not sure I understand how using indexOf and subString will get me a text string since they depend on integer values... Can someone show me some examples of how this might be done? Thanks
Ok figured out the basics, but I need it to extract every value in " " not just the first instance. The below extacts the value then converts the name into an id then replaces the name with an id, but ONLY does the first instance.
String unitIdStart = "\"";
String unitIdEnd = "\"~";
int unitIdStartIndex = searchText.indexOf(unitIdStart);
if( unitIdStartIndex != -1 ) {
int unitIdEndIndex = searchText.indexOf(unitIdEnd, unitIdStartIndex);
if( unitIdEndIndex != -1 );
{
String unitName = searchText.substring(unitIdStartIndex+1, unitIdEndIndex);
Unit backToId = UnitRepository.getIdFromName(unitName);
String unitId = backToId.getId().toString();
String searchTextWithUnitId = searchText.replace(unitName, unitId);

Related

How to control the comparator to avoid the , inside the " " in a csv file

I am trying to sort the values by age and I get an error. There is a method in the program where it separates the values by ",". Upon inspecting the error, it seems that it also considers the , inside the string address (which it shouldn't do). Any ideas as to how I can make it ignore the , inside the double quoted values?
Here's the part of the code where I split the values:
while ((string = input.readLine()) != null) { // Reads each line and loops until there is no more text to be read
String[] list = string.split(",", 8); // Uses "," to split the data
String name = list[0] + "," + list[1]; // The parts of data is assigned their specific variable
String email = list[2];// The parts of data is assigned their specific variable
String address = list[3];
int age = Integer.parseInt(list[4]); // Using parseInt, the data becomes an integer so comparison will be possible
String residency = list[5];
int district = Integer.parseInt(list[6]);
String gender = list[7];
person.add(new Person(name, email, address, age, residency, district, gender)); // Passes the information from the txt file
}

I am not able to make regex for the following String [duplicate]

I have a string like this:
"core/pages/viewemployee.jsff"
From this code, I need to get "viewemployee". How do I get this using Java?
Suppose that you have that string saved in a variable named myString.
String myString = "core/pages/viewemployee.jsff";
String newString = myString.substring(myString.lastIndexOf("/")+1, myString.indexOf("."));
But you need to make the same control before doing substring in this one, because if there aren't those characters you will get a "-1" from lastIndexOf(), or indexOf(), and it will break your substring invocation.
I suggest looking for the Javadoc documentation.
You can solve this with regex (given you only need a group of word characters between the last "/" and "."):
String str="core/pages/viewemployee.jsff";
str=str.replaceFirst(".*/(\\w+).*","$1");
System.out.println(str); //prints viewemployee
You can split the string first with "/" so that you can have each folder and the file name got separated. For this example, you will have "core", "pages" and "viewemployee.jsff". I assume you need the file name without the extension, so just apply same split action with "." seperator to the last token. You will have filename without extension.
String myStr = "core/pages/viewemployee.bak.jsff";
String[] tokens = myStr.split("/");
String[] fileNameTokens = tokens[tokens.length - 1].split("\\.");
String fileNameStr = "";
for(int i = 0; i < fileNameTokens.length - 1; i++) {
fileNameStr += fileNameTokens[i] + ".";
}
fileNameStr = fileNameStr.substring(0, fileNameStr.length() - 1);
System.out.print(fileNameStr) //--> "viewemployee.bak"
These are file paths. Consider using File.getName(), especially if you already have the File object:
File file = new File("core/pages/viewemployee.jsff");
String name = file.getName(); // --> "viewemployee.jsff"
And to remove the extension:
String res = name.split("\\.[^\\.]*$")[0]; // --> "viewemployee"
With this we can handle strings like "../viewemployee.2.jsff".
The regex matches the last dot, zero or more non-dots, and the end of the string. Then String.split() treats these as a delimiter, and ignores them. The array will always have one element, unless the original string is ..
The below will get you viewemployee.jsff:
int idx = fileName.replaceAll("\\", "/").lastIndexOf("/");
String fileNameWithExtn = idx >= 0 ? fileName.substring(idx + 1) : fileName;
To remove the file Extension and get only viewemployee, similarly:
idx = fileNameWithExtn.lastIndexOf(".");
String filename = idx >= 0 ? fileNameWithExtn.substring(0,idx) : fileNameWithExtn;

Android String format not working

I have a problem with String.format In android I want replace { 0 } with my id.
My this code not working:
String str = "abc&id={0}";
String result = String.format(str, "myId");
I think you should use replace method instead of format.
String str = "abc&id={0}";
str.replace("{0}","myId");
you have 2 ways to do that and you are mixing them :)
1.String format:
String str = "abc&id=%s";//note the format string appender %s
String result = String.format(str, "myId");
or
2.Message Format:
String str = "abc&id={0}"; // note the index here, in this case 0
String result = MessageFormat.format(str, "myId");
You have to set your integer value as a seperate variable.
String str = "abc&id";
int myId = 001;
String result = str+myId;
try this,
String result = String.format("abc&id=%s", "myId");
edit if you want more than one id,
String.format("abc&id=%s.id2=%s", "myId1", "myId2");
The syntax you're looking for is:
String str = "abc&id=%1$d";
String result = String.format(str, id);
$d because it's a decimal.
Other use case:
String.format("More %2$s for %1$s", "Steven", "coffee");
// ==> "More coffee for Steven"
which allows you to repeat an argument any number of times, at any position.

Matching input String pattern with a given string and separating w.r.t special characters

I have a piece of data in the following formats/patterns :
String inputFruit = "[Apple,Banana(Mango-Juice,lemon-Pickle,Grape-Drinks)]";
String inputFruit = "Apple,Banana(Mango-Juice,lemon-Pickle,Grape-Drinks)"
String inputFruit = "Apple(Mango-Juice,lemon-Pickle,Grape-Drinks)Banana"
Now I have to extract and store individual datas like :
firstFruit = Apple
secondFruit = Banana
miscFruit = Mango-Juice,lemon-Pickle,Grape-Drinks
I have the following code snippet which I am using :
public static void splitFruits(String inputFruit)
{
String firstFruit = StringUtils.EMPTY;
String secondFruit = StringUtils.EMPTY;
String miscFruit = StringUtils.EMPTY;
inputFruit = inputFruit.replaceAll("\\[" , "");
inputFruit = inputFruit.replaceAll("\\]" , "");
String frts[] = inputFruit.split("\\("");
String frtp[] = frts[0].split(",");
firstFruit = frtp[0];
secondFruit = frtp[1];
miscFruit = frts[1];
}
Here I need to store Apple in variable firstFruit, Banana in secondFruit, and whatever is there inside () in miscFruit.
My code is able to extract value for a specific patter mentioned in no 1.How can I create pattern match statements to match with input values in all the above specified 3 different formats and store them separately.
Instead of using frts[0] to get the first and second fruits, combine frts[0] and frts[2] (that is, the parts on either side of the parenthetical section) and split that.

Issue with Regular Expression

I made an application in which I can get a field's value through a regular expression with the help of a matcher... I made a method in which I pass a field and get a response. In string today I got some odd behaviour in my response I got AgentId = 25001220052805950 and after matcher I got fake so I have to check whether a field whose name contains "AgentId" exists and verify the values.
Needed Fields:
SecondaryAgentId=fake; PrimaryAgentId=fake;
Responce :
IsPrimaryAgentId=true; AgentId=25001220052805950; MerchantID=19; Cashier=michael; IsManualPayment=1; UserID=GraceRose; Password=rose1234; AmountUserEntered=2; AmountApproved=0; AmountDifference=0; Amount=0; CustomerNameAttempts=0; ProductID=Agriculture; InvoiceID=inv7443; SiteUrl=http://www.thcelink.com/index.php/shoping/checkout/step/step-1; ReturnURL=http://220.2.3:2027/Customer/Thanks.aspx; ResponseType=1; PrimaryAgentId=fake; PrimaryCurrencyCode=fake; SecondaryAgentId=fake; SecondaryCurrencyCode=fake; MerchantName=GraceRose; EmailId=rr#myglobal.com; Query1Attempts=0; MerchantTransactionID=543; MerchantTransactionSequenceID=246; txtAmtIsVisible=false; isQuery1Executed=false; isQuery2Executed=false; Voucher=fake; Passcode=fake; Error=fake; QueryType=fake; Payer=fake; CurrencyName=fake; CurrencySymbol=fake; CustomerName=fake; EmailBody=fake; ErrorText=fake; CustomerEmailID=fake; NavigatePageValue=0; IsCustomerInsertSucess=false; IdType=fake; IdNumber=fake; AggregateAttempts=0; Voucher2=fake; PassCode2=fake; Voucher3=fake; PassCode3=fake; TransCode=0; TransactionDate=2012-06-11T12:04:52.921875+05:30; NumberInWords=fake; MerchantCompany=fake; InvoiceNumber=fake; OverPaidAmount=0; InsufficientAmount=0; OverPaymentForEmail=fake; RedirectPage=false;
Update::
private String GetString1(String strManualproResponce2, String paternField) {
// TODO Auto-generated method stub
String s = null;
if(paternField.equalsIgnoreCase("AgentId"))
{
Pattern pinPattern2 = Pattern.compile("^"+paternField + "=(.*?);");
ArrayList<String> pins2 = new ArrayList<String>();
Matcher m2 = pinPattern2.matcher(strManualproResponce2);
while (m2.find()) {
pins2.add(m2.group(1));
s = m2.group(1);
}
}else
{
Pattern pinPattern2 = Pattern.compile(paternField + "=(.*?);");
ArrayList<String> pins2 = new ArrayList<String>();
Matcher m2 = pinPattern2.matcher(strManualproResponce2);
while (m2.find()) {
pins2.add(m2.group(1));
s = m2.group(1);
}
}
return s;
}
Your question is a little bit cryptic, from what I am understanding is that the code is not working for when you would like to match/extract the value for the AgentId field. The issue seems to be with your regular expression: "^"+paternField + "=(.*?);" assumes that the text AgentId will be at the beginning of your string, which is not since at the beginning of your string you have IsPrimaryAgentId.
Also, your current regex will return true both for IsPrimaryAgentId and AgentId since they both contain the substring: AgentId. To fix this, you can either use this regex: \\s+AgentId=(.*?);, this will require a white space before the AgentId text.
Another option would be (if your AgentId will always be numerical) to use this: AgentId=(\\d+);.

Categories