如何从Java中的String中提取日期和其他一些数值?

时间:2016-08-19 10:40:40

标签: java android regex

在String中有一些文本,如

  

有些文本bhla bhla。您的订单可享50%的折扣。一些文本..有效期至7月29日

如何从字符串中提取50%29 Jul
我不知道该怎么做。
哪种方法可以提取报价百分比并从该字符串中验证日期?

为此,我可以使用regex或任何其他过程来提取它。

帮我解决这个问题。

4 个答案:

答案 0 :(得分:2)

我猜使用Pattern和Matcher是最有说服力的方式

String text = "You have 50% off on your orders. Some texts.. Valid till 29 Jul";
Pattern pat = Pattern.compile("\\d+%");
Matcher match = pat.matcher(text);
if (match.find()) {
     System.out.println(match.group(0));
}
Pattern pat2 = Pattern.compile("\\d{1,2}\\s[A-z]{3}");
match = pat2.matcher(text);
if (match.find()) {
    System.out.println(match.group(0));
}
  

50%   
  7月29日

答案 1 :(得分:0)

您可以尝试类似

的内容
(\d+%).*?(\d{1,2}\s+(?:jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec))

您将获得两个捕获组。第一个持有百分比,第二个持有日期。

See it here at regex101

答案 2 :(得分:-1)

您必须使用Pattern来定义正则表达式,使用Matcher在文本中找到它。

例如,如果您知道验证码是超过6位的数字,则可以执行以下操作:

final String text1 = "Your Verification Code is 6457891";

final Pattern pattern = Pattern.compile("[0-9]{7,}");
final Matcher matcher = pattern.matcher(text1);
if (matcher.find()) {
    System.out.println(matcher.group()); //Prints 6457891
}

要查找日期,百分比或其他内容,您必须使用符合您要求的正则表达式编译模式,然后应用它。

通过使用模式和匹配器,您可以更进一步,只需找到您的值,您就可以知道字符串中的起始位置,结束,出现的次数以及许多其他有用的东西。

您可以在此处找到PatternMatcher官方文档。

答案 3 :(得分:-1)

你可以使用String的substring()方法,根据你的要求将其溢出。将它拆分为til为date和%使用indexof()函数并得到has和off索引然后通过substring()得到中间字符串。