search for a single quotes in a string and wrap it with other characters
I am trying to parse a csv file and in the process have come across some entries that contain single quotes. I have written the following regex to match more than one match of single quotes, iF the method returns true I am planning to wrap it in another set of characters however I am not getting the correct output
Below is the pseudo code:
public boolean containsChar()
{
String inputStr= "Niel O' Brian";
开发者_如何学Python
Pattern pattern = Pattern.compile("/'+");
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
return matchFound;
}
I would just use
String inputStr= "Niel O' Brian";
return inputStr.contains("'"); // same as your expression.
return inputStr.contains("''"); // I suspect this is what you are looking for.
If you have two consecutive single quotes you may want to replace them with one
return inputStr.replaceAll("''", "'");
You may want to place the whole string in double quotes if there is a single quote with
public static String quote(String text) {
if (text.contains("\"")
return '"' + text.replaceAll("\"", "\"\"") + '"';
if (text.contains(",") || text.contains("'"))
return '"' + text + '"';
return text;
}
its much neater to place double quotes around the whole field as Excel does.
You need to remove that forward slash. Right now you're searching for a /
followed by one or more single quotes.
Also, matches()
checks the entire string, you want find()
instead.
... I have written the following regex to match more than one match of single quotes ...
The regex '+
matches a single quote as well. To match more than one quote, use ''+
or the equivalent '{2,}
But if all you want is to find exactly two single quotes, I'd go for Peter's suggestion. I'll leave my answer because it explains why your matches()
fails.
精彩评论