来自远程服务的任意字符串。
根据Body:
子字符串的存在,我必须以各种方式解析它,我这样做:
String longString = service.getString();
if (longString.indexOf("Body:") != -1) {
// some code
} else {
// enother code
}
但是当字符串出现并看起来像Body:\Dsdqwe ....
逻辑从else
块运行时。我该如何解决?
答案 0 :(得分:0)
改为使用 -
String longString = service.getString();
if (longString.contains("Body:")) {
// some code
} else {
// enother code
}
答案 1 :(得分:0)
你可以试试这个,我想,
String longString = service.getString().replaceAll("\","");
if (longString.indexOf("Body:") != -1) {
// some code
} else {
// enother code
}
答案 2 :(得分:0)
这是一个非常有争议的问题。
我创建了以下名为'strings.txt'的文本文件:
Hallo Welt
Body:
Body:Content
Body:\Dasdf
一个小方法,它会读取每个字符串并根据您的支票对其进行测试:
public void foobar()
{
// As the character \D is an invalid escape sequence, you can not hard code it without using double \.
// But using double \ would change the actual input as in the process, so read the data from a file.
List<String> stringList = new ArrayList<>();
try (BufferedReader br = new BufferedReader(new FileReader("strings.txt"))) {
String line;
while ((line = br.readLine()) != null) {
stringList.add(line);
}
}
catch (Exception ex){
ex.printStackTrace();
}
// All strings are read from the file, now process and test each one of them
for(String str : stringList ) {
if (str.indexOf("Body:") != -1) {
System.out.println("'" + str + "' - Is containing the search term");
} else {
System.out.println("'" + str + "' - Is _NOT_ containing the search term");
}
}
}
这是我在运行上述内容时获得的输出:
'Hallo Welt' - Is _NOT_ containing the search term
'Body:' - Is containing the search term
'Body:Content' - Is containing the search term
'Body:\Dasdf' - Is containing the search term
结论:
如果您的程序收到类似Body:\Dasdf
的字符串,则可以正确处理它并且没有任何问题。问题的根源必须放在其他地方。
以下只是一些想法,问题可能来自:
您可以执行的步骤,以验证一些事项: