java 在字符串中搜索单引号并将其用其他字符包裹
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5948724/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
search for a single quotes in a string and wrap it with other characters
提问by ahaneo
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
我正在尝试解析一个 csv 文件,并且在此过程中遇到了一些包含单引号的条目。我编写了以下正则表达式来匹配多个单引号匹配项,如果该方法返回 true 我打算将其包装在另一组字符中,但是我没有得到正确的输出
Below is the pseudo code:
下面是伪代码:
public boolean containsChar()
{
String inputStr= "Niel O' Brian";
Pattern pattern = Pattern.compile("/'+");
Matcher matcher = pattern.matcher(inputStr);
boolean matchFound = matcher.matches();
return matchFound;
}
回答by Peter Lawrey
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.
像 Excel 那样在整个字段周围放置双引号要简洁得多。
回答by Bart Kiers
You need to remove that forward slash. Right now you're searching for a /
followed by one or more single quotes.
您需要删除该正斜杠。现在您正在搜索 a/
后跟一个或多个单引号。
Also, matches()
checks the entire string, you want find()
instead.
此外,matches()
检查整个字符串,find()
而不是你想要的。
... 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,}
正则表达式也'+
匹配单引号。要匹配多个引号,请使用''+
或等效'{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.
但是,如果您只想找到两个单引号,我会采纳 Peter 的建议。我会留下我的答案,因为它解释了您matches()
失败的原因。