简体   繁体   English

获取字符串的特定子字符串

[英]Obtaining a specific substring of a string

I was wondering if anyone could help. 我想知道是否有人可以提供帮助。 I have one big string which would be similar to below: 我有一个大字符串,类似于以下内容:

Name="firstName" Description="this is a test description" date="01/01/2016".  

What I want to do in java is to simply abstract a small part of this string, namely the bit after description which is in quotes which would ideally give me "this is a test description". 我想在Java中做的就是简单地提取此字符串的一小部分,即引号后的描述,理想情况下会给我“这是测试描述”。 Would anyone be able to guide me on how to achieve this? 有人可以指导我如何实现这一目标吗?

Thanks. 谢谢。

You can use the following regex: .*Description=\\"([\\\\w ]+)\\".*" . The string you want is capture group 1. For example: 您可以使用以下正则表达式: .*Description=\\"([\\\\w ]+)\\".*" 。您要的字符串是捕获组1。例如:

    Pattern pattern = Pattern.compile(".*Description=\"([\\w ]+)\".*");
    Matcher matcher = pattern.matcher(input);
    System.out.println(matcher.group(1));

If the string is exactly as you have there? 如果字符串与您那里的字符串完全一样?

Let's say the string looks like this, you could use split. 假设字符串看起来像这样,您可以使用split。

 String description = str.split("\"")[3];

This will give you exactly the part between the Description quotation marks, with just a split. 这将为您提供Description引号之间的精确部分,只是一个分隔。 You can run it here with a small example 您可以通过一个小例子在这里运行

As a small note: this assumes there are no " inside the actual content parts. (In firstname, I'm assuming this is a safe guess, but I'm not sure if the same can be said for the description part) 作为一个小提示:假定实际内容部分中没有" 。”(名,我假设这是一个安全的猜测,但是我不确定在描述部分是否可以说相同)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM