如何从给定的字符串获取子字符串?
我一直在使用class.The输出如何从给定的字符串获取子字符串?
String result=<?xml version="1.0"?><catalog><book id="bk101"><part1><date>Fri Apr 05 11:46:46 IST 2013</date><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price> <publish_date>2000-10-01</publish_date></part1></book></catalog>
现在我想先更换日期value.so我想从字符串中提取日期和更换新value.I读取整个XML文件作为单一字符串具有以下代码,
Date date=new Date()
String str=result.substring(result.indexOf("<date>"));
它显示从日期标记到结束标记的整个字符串。 如何提取日期标记并将其替换?
就值:
String str = result.substring(result.indexOf("<date>") + "<date>".length(),
result.indexOf("</date>"));
包括标签:
String str = result.substring(result.indexOf("<date>"),
result.indexOf("</date>") + "</date>".length());
String str=result.substring(result.indexOf("<date>") ,result.indexOf("</date>")+"</date>".length());
String#substring(int beginIndex)
返回一个新字符串,它是此字符串的一个子。子字符串 以指定索引处的字符开头,并扩展到该字符串的 结尾。
字符串#子(INT的beginIndex,诠释endIndex的)
返回一个新字符串,它是此字符串的一个子。子字符串 从指定的beginIndex开始,并扩展到 index endIndex - 1的字符。因此子字符串的长度为 endIndex-beginIndex。
谢谢,但它显示
这在这里得到使用正则表达式的标签的内容......但作为代替它 - 我会尽快给您回复。
String result = "<?xml version=\"1.0\"?><catalog><book id=\"bk101\"><part1><date>Fri Apr 05 11:46:46 IST 2013</date><author>Gambardella, Matthew</author><title>XML Developer's Guide</title><genre>Computer</genre><price>44.95</price> <publish_date>2000-10-01</publish_date></part1></book></catalog>";
String pattern = ".*(?i)(<date.*?>)(.+?)(</date>).*";
System.out.println(result.replaceAll(pattern, "$2"));
干杯
编辑:哦,你在Java想要它。这是C#解决方案=)
您可以通过替换包括标记在内的整个日期来解决此问题。
你在XML中有两个日期,所以为了确保你不会替换它们,你可以这样做。
int index1 = result.IndexOf("<date>");
int index2 = result.IndexOf("</date>") - index1 + "</date>".Length;
var stringToReplace = result.Substring(index1, index2);
var newResult = result.Replace(stringToReplace, "<date>" + "The Date that you want to insert" + "</date>");
为什么不使用内置的XML解析API? – MadProgrammer 2013-04-05 09:23:53
String str = result.substring(result.indexOf(“”),result.indexOf(“ ”)); –
2013-04-05 09:25:46
你可以使用正则表达式 – 2013-04-05 09:26:24