[英]Getting a specific word in a string
I am new to java, i have a string 我是Java新手,我有一个字符串
"rdl_mod_id:0123456789\n\nrdl_mod_name:Driving Test\n\nrdl_mod_type:PUBL\n\nrdl_mod_mode:Practice\n\nrdl_mod_date:2013-04-23"
What I want is to get the Driving Test
word. 我想要得到Driving Test
单词。 The word is dynamically changes so what I want to happen is get the word between the rdl_mod_name:
and the \\n
. 这个词是动态变化的,所以我想发生的事情是在rdl_mod_name:
和\\n
之间得到一个词。
I would look into java regular expressions (regex). 我将研究Java正则表达式(regex)。 The String matches method uses a regex to determine if there's a pattern in a string. 字符串匹配方法使用正则表达式来确定字符串中是否存在模式。 For what you are doing, I would probably use 'matches(rdl_mod_.*\\n)'. 对于您正在做的事情,我可能会使用'matches(rdl_mod _。* \\ n)'。 The '.*' is a wildcard for strings, so in this context it means anything between rdl_mod and \\n. “。*”是字符串的通配符,因此在这种情况下,它表示rdl_mod和\\ n之间的任何内容。 I'm not sure if the matches method can process forward slashes (they signify special text characters), so you might have to replace them with either a different character or remove them altogether. 我不确定matchs方法是否可以处理正斜杠(它们表示特殊文本字符),因此您可能必须用其他字符替换它们或将其完全删除。
Use java's substring() function with java indexof() function.
Try the following.. It will work in your case.. 请尝试以下操作。它会根据您的情况起作用。
String str = "rdl_mod_id:0123456789\n\nrdl_mod_name:Driving Test\n\nrdl_mod_type:PUBL\n\nrdl_mod_mode:Practice\n\nrdl_mod_date:2013-04-23";
Pattern pattern = Pattern.compile("rdl_mod_name:(.*?)\n");
Matcher matcher = pattern.matcher(str);
while (matcher.find()) {
System.out.println(matcher.group(1));
}
Also you can make use of regex
, matcher
, pattern
to get your desired result.. 您也可以使用regex
, matcher
, pattern
获得所需的结果。
The following links will also give you a fair idea: 以下链接也将使您有一个不错的主意:
Extract string between two strings in java 在Java中提取两个字符串之间的字符串
Java- Extract part of a string between two special characters Java-提取两个特殊字符之间的字符串的一部分
Try this code : 试试这个代码:
String s = "rdl_mod_id:0123456789\n\nrdl_mod_name:Driving Test\n\nrdl_mod_type:PUBL\n\nrdl_mod_mode:Practice\n\nrdl_mod_date:2013-04-23";
String sArr[] = s.split("\n\n");
String[] sArr1 = sArr[1].split(":");
System.out.println("sArr1[1] : " + sArr1[1]);
The s.split("\\n\\n");
s.split("\\n\\n");
will split the string on basis of \\n\\n
. 将基于\\n\\n
拆分字符串。 The second split ie sArr[1].split(":");
第二个分割,即sArr[1].split(":");
will split the second element in array sArr on basis of :
ie split rdl_mod_name:Driving Test into rdl_mod_name and Driving Test. 将基于以下内容拆分数组sArr中的第二个元素:
即将rdl_mod_name:Driving Test拆分为rdl_mod_name和Driving Test。 sArr1[1]
is your desired result. sArr1[1]
是您想要的结果。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.