I want to extract a string between two characters "#" and the first ".".I just tried the code but my code is not appropriate and getting different output
//code
static String method(String s){
String result=s.substring(s.lastIndexOf("#"));
int index = result.indexOf(".");
String finalResult= result.substring(0,index);
return finalResult;//return
}
eg:abc#gmail.com
my output:#gmail
Expected output: gmail
From input gmail is identifies as a string between '#' and the first '.' after it.
But i am getting # in my output which is different from expected output. Help me out.
As per Javadocs:
Returns a string that is a substring of this string. The substring
begins with the character at the specified index and extends to the
end of this string.
Examples:
"unhappy".substring(2) returns "happy"
"Harbison".substring(3) returns "bison"
"emptiness".substring(9) returns "" //(an empty string because there are no more characters after the 9th, i.e., there's no 10th character in "emptiness"; "emptiness" is a 9-letter word)
And if you debug your code, you will see
System.out.println("abc#gmail.com".lastIndexOf("#"));
produces 3
As mentioned by Scary Wombat, substring(position) is inclusive, and therefore s.substring(s.lastIndexOf("#")); will return substring containing '#' char.
Some extra note is that there are be many edge cases for which your code will fail, for example null string, string that does not contain '#' etc.
See suggestion code that tries to catch all edge cases, with test
#Test
public void testGetSubString(){
final String constant = "gmail";
final String input1 = "test#gmail.com";
final String input2 = "t.est#gmail.com";
final String input3 = "test##gmail.com";
final String input4ShouldBeNull = "test#gmailcom";
final String input5ShouldBeNull = "test#.gmailcom";
final String input6ShouldBeNull = "";
final String input7ShouldBeNull = null;
final String input8ShouldBeNull = "gmail.com";
assertEquals(constant, getSubString(input1));
assertEquals(constant, getSubString(input2));
assertEquals(constant, getSubString(input3));
assertNull(constant, getSubString(input4ShouldBeNull));
assertNull(constant, getSubString(input5ShouldBeNull));
assertNull(constant, getSubString(input6ShouldBeNull));
assertNull(constant, getSubString(input7ShouldBeNull));
assertNull(constant, getSubString(input8ShouldBeNull));
}
public String getSubString(final String input) {
if(input == null) {
return null;
}
final int indexOfAt = input.lastIndexOf('#');
if(input.isEmpty() || indexOfAt < 0 || indexOfAt >= input.length()-2) {
return null;
}
String suffix = input.substring(indexOfAt + 1);
final int indexOfDot = suffix.indexOf('.');
if(indexOfDot < 1) {
return null;
}
return suffix.substring(0, indexOfDot);
}
Related
I have this string:
String string = "The status is %status(" + randomString + ")%";
How can I replace the part between percent signs with anything, but without knowing randomString?
You can use String.replaceAll. An example:
String randomString = "asdf";
String string = "The status is %status(" + randomString + ")%";
String replacement = "myStatus";
String fString = string.replaceAll("%status(.*)%", replacement);
System.out.println(fString);
Which outputs:
The status is myStatus
The regex you want to use is %(.+)%, which matches %status(foo)% and %status(asidh37887123-48hsZXas;;fgfg)%.
To replace it, you can do string.replaceAll("%(.+)%", "anything").
This will turn The status is %status(foo)% to The status is anything.
Two ways to do it :
String string = "The status is %status(aaaaaaaaaaaaaaa)%";
int x = string.indexOf("%");
int y = string.lastIndexOf("%");
System.out.println(x);
System.out.println(y);
string = string.substring(0,x)+string.substring(y+1,string.length());
System.out.println(string);
string = "The status is %status(aaaaaaaaaaaaaaa)%";
string = string.replaceAll("%.+%", "");
System.out.println(string);
Result :
This question already has answers here:
Split string on spaces in Java, except if between quotes (i.e. treat \"hello world\" as one token) [duplicate]
(1 answer)
Tokenizing a String but ignoring delimiters within quotes
(14 answers)
Closed 6 years ago.
Hi I am new to Java and trying to use the split method provided by java.
The input is a String in the following format
broadcast message "Shubham Agiwal"
The desired output requirement is to get an array with the following elements
["broadcast","message","Shubham Agiwal"]
My code is as follows
String str="broadcast message \"Shubham Agiwal\"";
for(int i=0;i<str.split(" ").length;i++){
System.out.println(str.split(" ")[i]);
}
The output I obtained from the above code is
["broadcast","message","\"Shubham","Agiwal\""]
Can somebody let me what I need to change in my code to get the desired output as mentioned above?
this is hard to split string directly.So, i will use the '\t' to replace
the whitespace if the whitespace is out of "". My code is below, you can try it, and maybe others will have better solution, we can discuss it too.
package com.code.stackoverflow;
/**
* Created by jiangchao on 2016/10/24.
*/
public class Main {
public static void main(String args[]) {
String str="broadcast message \"Shubham Agiwal\"";
char []chs = str.toCharArray();
StringBuilder sb = new StringBuilder();
/*
* false: means that I am out of the ""
* true: means that I am in the ""
*/
boolean flag = false;
for (Character c : chs) {
if (c == '\"') {
flag = !flag;
continue;
}
if (flag == false && c == ' ') {
sb.append("\t");
continue;
}
sb.append(c);
}
String []strs = sb.toString().split("\t");
for (String s : strs) {
System.out.println(s);
}
}
}
This is tedious but it works. The only problem is that if the whitespace in quotes is a tab or other white space delimiter it gets replaced with a space character.
String str = "broadcast message \"Shubham Agiwal\" better \"Hello java World\"";
Scanner scanner = new Scanner(str).useDelimiter("\\s");
while(scanner.hasNext()) {
String token = scanner.next();
if ( token.startsWith("\"")) { //Concatenate until we see a closing quote
token = token.substring(1);
String nextTokenInQuotes = null;
do {
nextTokenInQuotes = scanner.next();
token += " ";
token += nextTokenInQuotes;
}while(!nextTokenInQuotes.endsWith("\""));
token = token.substring(0,token.length()-1); //Get rid of trailing quote
}
System.out.println("Token is:" + token);
}
This produces the following output:
Token is:broadcast
Token is:message
Token is:Shubham Agiwal
Token is:better
Token is:Hello java World
public static void main(String[] arg){
String str = "broadcast message \"Shubham Agiwal\"";
//First split
String strs[] = str.split("\\s\"");
//Second split for the first part(Key part)
String[] first = strs[0].split(" ");
for(String st:first){
System.out.println(st);
}
//Append " in front of the last part(Value part)
System.out.println("\""+strs[1]);
}
I need to extract a mobile number from a string. I have extracted numbers from string, but failed to get what I need.
Here is the input: a string contains an address and phone number.
String input = "Street1,Punjab Market-Patiala 147001 M:92166-29903"
I need to extract the mobile number, which is 92166-29903.
I use this method to check whether a string contains a mobile number or not:
private Boolean isMobileAvailable(String string)
{
Boolean ismobile = false;
if (string.matches("(?i).*M.*"))
{
ismobile = true;
}
return ismobile;
}
Used in a code as follows:
String mobilenumber="";
private void getMobileNumber(String sample)
{
int index = sample.indexOf("M");
String newString = "";
newString = sample.substring(index, sample.length());
mobileNumber = newString.replaceAll("[^0-9]", "");
edtMobile.setText(mobileNumber.substring(0, 10));
}
Here, instead of mobile number, I am getting 147009211.
How can I identify the mobile number correctly from above string?
int index = sample.lastIndexOf("M");
String newString = sample.substring(index+2, sample.length());
mobileNumber = newString.replaceAll("[^0-9]", "");
edtMobile.setText(mobileNumber.substring(0, 10));
If you want the "-" in your result,just delete mobileNumber = newString.replaceAll("[^0-9]", "");
try this code.
Method 1:
String input = "Street1,Punjab Market-Patiala 147001 M:92166-29903";
int value = input.lastIndexOf(":");
String s = input.substring(value + 1, input.length());
Log.d("reverseString", "" + s);
Method 2:
StringBuffer reverseString=new StringBuffer(input);
StringBuffer s1=reverseString.reverse();
int firstindex=s1.indexOf(":");
String finalstring=s1.substring(0, firstindex);
StringBuffer getexactstring=new StringBuffer(finalstring);
this code will give you exact mobile number that you want.
I am having the below string in a string variable in java.
rule "6"
no-loop true
when
then
String prefix = null;
prefix = "900";
String style = null;
style = "490";
String grade = null;
grade = "GL";
double basePrice = 0.0;
basePrice = 837.00;
String ruleName = null;
ruleName = "SIVM_BASE_PRICE_006
Rahul Kumar Singh";
ProductConfigurationCreator.createFact(drools, prefix, style,grade,baseprice,rulename);
end
rule "5"
no-loop true
when
then
String prefix = null;
prefix = "800";
String style = null;
style = "481";
String grade = null;
grade = "FL";
double basePrice = 0.0;
basePrice = 882.00;
String ruleName = null;
ruleName = "SIVM_BASE_PRICE_005";
ProductConfigurationCreator.createFact(drools, prefix, style,grade,baseprice,rulename);
end
I need to replace this the carriage return between "THEN" and "END" keyword with white space so that it becomes like below code:
rule "6"
no-loop true
when
then
String prefix = null;
prefix = "900";
String style = null;
style = "490";
String grade = null;
grade = "GL";
double basePrice = 0.0;
basePrice = 837.00;
String ruleName = null;
ruleName = "SIVM_BASE_PRICE_006 Rahul Kumar Singh";
ProductConfigurationCreator.createFact(drools, prefix, style,grade,baseprice,rulename);
end
rule "5"
no-loop true
when
then
String prefix = null;
prefix = "800";
String style = null;
style = "481";
String grade = null;
grade = "FL";
double basePrice = 0.0;
basePrice = 882.00;
String ruleName = null;
ruleName = "SIVM_BASE_PRICE_005";
ProductConfigurationCreator.createFact(drools, prefix, style,grade,baseprice,rulename);
end
In the above two example of string set, the second is correct format that I need. However, in the first set, I am getting this :
ruleName = "SIVM_BASE_PRICE_006
Rahul Kumar Singh";
This perticulerly needs to be like this:
ruleName = "SIVM_BASE_PRICE_006 Rahul Kumar Singh";
and I also need to ensure that this doesn't effect any thing else in the string.
Thus I need to replace this "carriage return" with a white space and make in one line. This is my requirment. I tried with replace and replaceAll method of string but not works properly.
Problem:
I need to look in between string "then" and "end" and in that whenever
there is any carriage return in between two double quaotes "" ""; I
need to replace this carriage return with white space and make it in
one line.
Thanks
EDIT:
DRT:
template header
Prefix
Style
Product
package com.xx
import com.xx.drools.ProductConfigurationCreator;
template "ProductSetUp"
rule "Product_#{row.rowNumber}"
no-loop true
when
then
String prefix = null;
prefix = "#{Prefix}";
String style = null;
prefix = "#{Style}";
String product = null;
product = "#{Product}";
ProductConfigurationCreator.createProductFact(drools,prefix,style,product);
end
end template
The excel and drt are for only demostration purpose.
In the Image, in Product column, there is "SOFAS \rkumar shorav". Actually this is creating problem. This will generate like below:
product = "SOFAS
kumar shorav";
I need this like below:
product = "SOFAS kumar shorav";
Then Excel data :
attached image.
Instead of regex I would probably write my own formatter which will
check if cursor is inside quote
replace each \r with space
replace each \n with space, unless it was placed right after \r which means that space was already placed for that \r
write rest of characters without change.
Only possible problem is that this formatter will not care about where string is placed so if you want to format some specific part of the string you will need to provide only that part.
Code implementing such formatter can look like:
public static String format(String text){
StringBuilder sb = new StringBuilder();
boolean insideQuote = false;
char previous = '\0';//to track `\r\n`
for (char ch : text.toCharArray()) {
if (insideQuote &&
(ch == '\r' ||
ch == '\n' && previous != '\r') ) {
sb.append(" ");//replace `\r` or `\n` with space
}else {
if (ch == '"') {
insideQuote = !insideQuote;
}
sb.append(ch); //write other characters without change
}
previous = ch;
}
return sb.toString();
}
helper utility method
public static String format(File file, String encoding) throws IOException {
String text = new String(Files.readAllBytes(file.toPath()), encoding);
return format(text);
}
Usage:
String formatted = format(new File("input.txt"), "utf-8");
System.out.println(formatted);
You might say that there is a bug in org.drools.template.parser.StringCell, method
public void addValue(Map<String, Object> vars) {
vars.put(column.getName(), value);
}
Here, the value is added to the Map as a String but this does not take into account that string values are usually expanded into string literals. Therefore, an embedded newline should be converted to the escape sequence \n. You might try this patch:
public void addValue(Map<String, Object> vars) {
String h = value.replaceAll( "\n", "\\\\n" );
vars.put(column.getName(), h);
}
Take the source file, put it into a suitable subdirectory, compile it to a class file and make sure that the root directory precedes drools-templates-6.2.0.Final-sources.jar in the class path. You should then see
ruleName = "SIVM_BASE_PRICE_006\nRahul Kumar Singh";
in the generated DRL file. Obviously, this is not a space, but it is what is written in the spreadsheet cell!
I suggest (urgently) that you do not follow this approach. The reason is simply this that strings are not always expanded between quotes, and then the replacement would result almost certainly in invalid code. There is simply no remedy as the template compiler is "dumb" and does not really "know" what it is expanding.
If a String in a spreadsheet contains a line break, template expansion must render this faithfully, and break the line just there. If this produces invalid (Java) code: why was the line break entered in the first place? There is absolutely no reason not to have a space in that cell if that's what you want.
s = s.replaceAll("(?m)^([^\"]*(\"[^\"]*\")*[^\"]*\"[^\"]*)\r?\n\\s*", "$1 ");
This replaces lines with an unpaired quotes to one with the line ending replaced.
^.... means starting at the line begin
[^\"] means not quote
\r?\n catches both CR+LF (Windows) as LF (Rest) line endings
not-quotes,
repetition of " not-quotes ",
not quotes, quote, not-quotes, newline
Mind this does not cover backslash+quote, escapes them-selves.
Use the "multi line" flag:
str = str.replaceAll("(?m)^\\s+", "");
The multi-line flag (?m) makes ^ and $ match start/end of each line (rather than start/end of input). \s+ means "one or more whitespace characters".
Hi i am having string like " MOTOR PRIVATE CAR-PACKAGE POLICY " . Now i want remove last two words and add hyphen between words finally i want string like " MOTOR-PRIVATE-CAR' . I tried many times using string methods in java but could not find exactly. Can anyone give a solution for that . Give me a code is plus for me.
Thanks in advance
public class StringModify {
public static void main(String[] args) {
try {
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
System.out.println("Value-------------------->"+value.replaceFirst("\\s*\\w+\\s+\\w+$", ""));
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can do it with the help of substring() and replaceAll() methods
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
value = value.substring(0, value.indexOf("-")); //get the string till -
value = value.replaceAll("\\s", "-"); //replace all the space chars with -
System.out.println(value);
I have used String.replaceAll() instead of String.replace() to use the regex for white space
\s stands for white space character and and while adding it as regex, we need to escape it with an extra \ so --> \\s
indexOf("-") method returns the index of first occurrence of the String passed, which should be the 2nd parameter to substring method, which is the endIndex
You can do it in two steps:
To get all the words from the string before "-", you can use String
substring and indexOf methods.
To replace empty spaces with hiphen(-), you can use the String replace method.
Here is the code:
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
value = value.substring(0,value.indexOf("-")); // get the words before "-"
value = value.replace(" ", "-"); // replace space with hiphen
System.out.println(value);
public class StringModify {
/**
* #param args
*/
public static void main(String[] args) {
try {
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
System.out.println("Value-------------------->"+value.replaceFirst("\\s*\\w+\\s+\\w+$", ""));
value = value.substring(0,value.indexOf("-")); // get the words before "-"
value = value.replace(" ", "-"); // replace space with hiphen
System.out.println(value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can split the string with '-' which gives you the part of the string in which you need to insert ' '. Split the string again with ' ' and insert '-' b/w the words.
String value="MOTOR PRIVATE CAR-PACKAGE POLICY";
String[] phrase = value.split("-");
String[] words = phrase[0].split(" ");
String newValue;
for(int i = 0; i < words.length; i++)
newValue += words[i] + "-";
String var = "/";
String query = "INSERT INTO Recieptnumbersetup VALUES('"+Prestring+"' '"+var+"','"+var+"' '"+post string+"')" ;
PS = connection.PrepareStatement(query);
Use this i have used slash over here i was having same problem.