contains quotation mark java - java

how to I add an argument to check if a string contains ONE quotation mark ? I tried to escape the character but it doesn't work
words[i].contains()
EDIT: my bad, got some unclosed brackets, works fine now

words[i].matches("[^\"]*\"[^\"]*")
That is: any non-quotes, a quote, any non-quotes.

You could use something like this:
words[i].split("\"").length - 1
That would give you the amount of "s in your string. Therefore, just use:
if (words[i].split("\"").length == 2) {
//do stuff
}

You can check if the first quotation mark exists, and then check if the second one doesn't. It's much faster than using matches or split.
int index = words[i].indexOf('\"');
if (index != -1 && words[i].indexOf('\"', index + 1) == -1){
// do stuff
}

To check number or quotes you can also use length of string after removing ".
int quotesNumber = words[i].length() - words[i].replace("\"", "").length();
if (quotesNumber == 1){
//do stuff
}

Related

how to escape escape characters in Java

I have a large file that contains \' that I need to find. I've tried variations of the following but it's not working:
do{
line = TextFileIO.readLine(bufferedReader);
if(line != null){
TextFileIO.writeLine(bufferedWriter,line);
for (int i = 0; i < line.length() - 1; i++){
if(line.substring(i,i+1).equals("\\\'"))System.out.println("we found it " + line);
}
}
}while (line != null);
No need to escape the single quote!
Single quotes don't need escaping because all Java strings are delimited by double quotes. Single quotes delimit character literals. So in a character literal, you need to escape single quotes, e.g. '\''.
So all you need is "\\'", escaping only the backslash.
substring(i,i+1) cannot produce a two character string. If you are trying to get 2-character strings, you need to call with (i,i+2).
Also, your for loop can be replaced by a call to contains.
if(line.contains("\\'"))System.out.println("we found it " + line);
To represent a single backslash followed by an apostrophe, you can use
"\\'"
But there is no way substring(i,i+1) can be equal to a two-character string.
Perhaps you mean
if (line.substring(i, i+2).equals("\\'")) ...
line.substring(i,i+1) only contains one character, and the for loop can replaced by line.indexOf("\\'") >= 0:
if (line.indexOf() >= 0) {
System.out.println("we found it " + line);
}
\\ is an escaped \ in Java, so I think your match string should be "\\".
P.s. I'm not exactly sure what you are trying to achieve here, but there appears to be more elegant, more "java-like" ways to do it than what you have here...

Extract AND condition in SQL statement via java regex

i want to get sql and conditions in a sql statement
Input:
And tbl.col1='Jim And Tom' and tbl.col2 like '%Test' AND tbl.col3 >='2018-12-12' And tbl.col4 Like 'what's this'
Expected output
tbl.col1='Jim And Tom'
tbl.col2 like '%Test'
tbl.col3 >='2018-12-12'
tbl.col4 Like 'what's this'
Btw, i have tried java split to do this, but if the keyword contains and, it will not work
String[] subFilters = Pattern.compile("\\s*and\\s*",Pattern.CASE_INSENSITIVE).split(filter);
If it's possible to get output via java regex?
Try this out:
String s = "And condition 1 here and tbl.col2 like '%Test' AND tbl.col3 >='2018-12-12' And tbl.col4 Like 'what\\'s this'";
s = s.trim();
s = s.substring(3).trim();
boolean exclude = false;
s = s + " and";
String str = "";
for(int i = 0; i < s.length()-3; i++)
{
if( s.charAt(i) == '\'' && !(s.charAt(i-1) == '\\') )
{
exclude = !exclude;
}
if((!s.substring(i, i+3).equalsIgnoreCase("and") || exclude) && (i != s.length()-4))
{
str += s.charAt(i);
}
else
{
System.out.println(str);
str = "";
i += 3;
}
}
Note - The above code should work for pretty much any condition type, but as Wiktor has mentioned in the comments, you'll need to use 'what\\'s this' instead of 'what's this'
Explanation -
When exclude is true, it means that the letters (and essentially words) being checked are within ' '. Hence, str stores ANY AND ALL characters within the ' ', including the notorious and
i < s.length() - 3 means that the characters being checked and stored will be those before three letters of the end of the String. It's important, because we have added an " and" to s previously.
Now, if the letter at i is ', and is not preceded by a \, then the value of exclude is reversed i.e. if the system was being told to include all words, even and, then it is told not to, now. Hence, any and within quotations is captured using this method.
if((!s.substring(i, i+3).equalsIgnoreCase("and") || exclude) && (i != s.length()-4)) is a very tedious way to say that if the letter is not part of an and separator, (or if it the last letter of the final condition), then it should be stored in str.
It's quite difficult to type out the best explanation possible, but I'm sure if you read the code long and hard enough, then you'll understand it better.

Remove Whitespaces ONLY at the end of a String (java) [duplicate]

This question already has answers here:
How to remove only trailing spaces of a string in Java and keep leading spaces?
(10 answers)
Closed 5 years ago.
i already found similar topics but they were not really helpful.
I basically need to know how I can remove whitespaces ONLY at the end of a string.
For example: String a = "Good Morning it is a nice day ";
Should be: String a = "Good Morning it is a nice day";
You see there are like three whitespaces at the end or something. I got replaceAll() as a suggestion but as I said I only want to remove the remaining whitespaces at the end. How do I do that ? I already tried different things like going through the String like this:
for(int i = a.length(); i > a.length() - 3; i++){
if(a.charAt(i) == ' '){
<insert Solution here>
}
}
With the code above I wanted to check the last three Chars of the string because it is sufficient. It is sufficient for the stuff I want to do. There wont be a case with 99+ whitespaces at the end (probably).
But as you see I still dont know which method to use or if this is actually the right way.
Any suggestions please ?
If your goal is to cut only the trailing white space characters and to save leading white space characters of your String, you can use String class' replaceFirst() method:
String yourString = " my text. ";
String cutTrailingWhiteSpaceCharacters = yourString.replaceFirst("\\s++$", "");
\\s++ - one or more white space characters (use of possesive quantifiers (take a look at Pattern class in the Java API documentation, you have listed all of the special characters used in reguĊ‚ar expressions there)),
$ - end of string
You might also want to take a look at part of my answer before the edit:
If you don't care about the leading white space characters of your input String:
String class provides a trim() method. It might be quick solution in your case as it cuts leading and trailing whitespaces of the given String.
You can either use the regular expression:
a = a.replaceAll("\\s+$", "");
to remove trailing whitespaces and store the result back into a
or using a for loop:
String a = "Good Morning it is a nice day ";
StringBuilder temp = new StringBuilder(a);
for( int i = temp.length() - 1 ; i >= 0; i--){
if(temp.charAt(i) == ' '){
temp.deleteCharAt(i);
}else{
break;
}
}
a = temp.toString();
a = ("X" + a).trim().substring(1);
int counter = 0;
String newWord = "";
for(int i = 0; i < word.length(); i++){
if (word.charAt(i) == " "){
counter++;
}
else {
counter = 0;
}
if (counter > 1){
newWord = word.substring(0, i);
break;
}
else {
newWord = word;
}
}
The solution would look something like this.

String search with "?" as a joker?

I have an ArrayList of strings and I want to perform a search method on them.
So far I only have this:
public void searchNote(String searchCertainNote)
{
for (String note: notes)
{
if (note.contains(searchCertainNote))
{
System.out.println(note);
}
}
}
I would like to improve this search method a bit by allowing the user to search for a string like:
String searchCertainString = "a?c"
... Possible search results: "abcd"; "a4c"; "Abc", "a22c", "a$c", etc...
The question mark "?" should represent all characters that are out there.
I did some googling and found out that I could implement this by using regex and String.matches() ...
But I still need your help on this!
Thanks =)
If the user will be entering a '?' as the wildcard (or joker as you called it), then, if you use Regex, you'll need to convert the '?' to '.' to use it in the Regex pattern. In Regex, the period matches any single character.
So, you'd need to change the user's input of "a?b" to "a.b".
If the '?' is meant to match at least one character, but possible more than one, then use '.+' instead. The '+' is a qualifier that means 'one or more of the preceding thing'.
So, you'd need to change the user's input of "a?b" to "a.+b". This pattern will match "axb" "axyb", but not "ab".
Here's a good beginner's guide for Java regular expression handling:
http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
Do this:
if(searchCertainNote.length <= 0) {
// String is empty, do something
return;
}
for(int i = 0; i < searchCertainNote.length; i++) {
if(searchCertainNote.charAt(i) == 'a') {
if(searchCertainNote.length >= ((i + 1) + 1))) {
if(searchCertainNote.charAt(i + 2) == 'c') {
System.out.println(searchCertainNote.charAt(i) + searchCertainNote.charAt(i + 1) + searchCertainNote.charAt(i + 2));
return;
}
} else {
// Not found, so do something
return;
}
}
}
You can trust completely on this code. It will print to screen a?c if found in ANY string that you enter and return, else it will do something you want and returns. It also detects empty and too short strings and avoids an ArrayIndexOutOfBoundsException. Good luck :D.

Using "Predefined character classes" on a substring

I want to check the last character of the String for characters that are not a non-word character using '\W' and allow certain symbols like ". , ! etc" from the top of my head I thought of using a code similar to this.
Boolean notCompleted = true;
int deduct = 1;
while(notCompleted){
if(string.charAt(string.length() -deduct) == '\W'){ // '\W' <-- doesn't work since it accepts anything other than "escape sequences".
if(string.charAt(string.length() -deduct) == '.'||string.charAt(string.length() -deduct) == ','||string.charAt(string.length() -deduct) == '!'){
//Do nothing and move on to the while loop
}else{
//Replace the non word character with ' '.
}
}
deduct++;
if(deduct >= html.length()){
notCompleted = false;
}
}
The reason why this doesn't work is because using string.charAt only accepts "Escapes sequence".
My question is there another way to pull this off rather than doing.
string.replaceAll("\W", "");
All suggestions is greatly appreciated. Thank you.
Thanks to the tip npinti gave me I built this code. However I am getting an error line
Desired Result of fakeNewString as requested should be "! asdsdefwef.,a,,sda.sd";
fakeNewString = sb.toString(); // NullPointerException
public static void test5(){
Boolean notCompleted = true;
String fakeNewString = "!##$%^&*( asdsdefwef.,a,,sda.sd";
int start = 0, end = 1;
StringBuilder sb = null;
try{
while(notCompleted){
start++;
String tempString = fakeNewString.substring(start, end);
if(Pattern.matches("\\W$", tempString)){
if(Pattern.matches("!", tempString)||Pattern.matches(".", tempString)||Pattern.matches(",", tempString)||Pattern.matches("\"", tempString)){
//do nothing
sb.append(tempString);
}else{
//Change it to spaces.
tempString = " ";
sb.append(tempString);
}
}
end++;
if(end >= fakeNewString.length()){
notCompleted = false;
fakeNewString = sb.toString();
System.out.println(fakeNewString);
}
}
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}
}
You can do something like so:
Pattern pattern = Pattern.compile("\\W$");
Matcher matcher = pattern.match(string);
if (matcher.find())
{
//do something when the string ends with a non word character
}
Take a look at this tutorial for more information on regular expressions.
You can use String.replaceAll in a slightly different way to do this. It achieves the same effect as the code you're trying to write, which seems like a complex solution for a simple problem. Try this code:
string.replaceAll("[^\\w!,.]", " ");
All the invalid characters are now replaced by a space, and multiple sequential occurrences of them are replaced by multiple spaces.
Lets try to break down the question (desire) and answer it:
I want to check the last character of the String for characters that are not a non-word character using '\W' and allow certain symbols like ". , ! etc"
First we have:
I want to check the last character of the String
Expression for character X at end of string:
X$
Then:
for characters that are not a non-word character
Expression:
[^\W] i.e. \w
And also:
allow certain symbols like ". , ! etc"
Added to the expression above:
[\w.,!]
And the combined final result is:
[\w.,!]$
Ta-da! (Altho I'm guessing OP is looking for something else, I did it for teh lulz.)

Categories

Resources