首页 > 解决方案 > 如何使用正则表达式从字符串中解析某些数字?

问题描述

我有一个任务,我必须以这种方式从字符串中解析某些数字,

如果我将此字符串传递给方法,例如以下字符串:

*I bought 2 books in (2005), They were pretty good, but i didn't like the mention of god in it, 32(1-5), 214-443.

它应该打印版本:32,从 214 到 443 页

*have you read the book published in (2009), named The art of being selfish, look at page, 87, 104-105.

它应该打印版本:87,第 104 到 105 页

*Please take a look here in this link, you will find the, 10(3-4), 259-271.

它应该打印版本:10,从 259 到 271 页

*Someone help me here please in the look for it book, 5(1), 1-4

它应该打印版本:5,从 1 到 4 页

*Help needed (here), 8(4), 325-362.

它应该打印版本:8,从 325 到 362 页

I'm having trouble with the regex formatting since it is required.

解决方案

我在我的解决方案中写的

  public static void main(String[] args) {
    String testString = "Help needed (here), 8(4), 325-362.";
    stringParser(testString);
  }

  static void stringParser(String string) {
    List<String> pages = getPages(string);
    String edition = getEdition(string);

    System.out.println("Edition: " + edition +", pages from " + pages);
  }

  static List<String> getPages(String string) {
    List<String> pages = new ArrayList<>();
    Pattern ptr = Pattern.compile(">();(?<=\\w[,]\\s)[0-9]*");
    Matcher match = ptr.matcher(string);
    while (match.find()) {
      pages.add(match.group());
    }
    return pages;
  }
  static String getEdition(String string) {
    String edition = "0";
    Pattern ptr = Pattern.compile("(?<=(\\d|[)])[,]\\s)\\d.*");
    Matcher match = ptr.matcher(string);
    if (match.find()) {
      edition = match.group();
    }
    return edition;
  }

使用所需句子链接到 Regex101 https://regex101.com/r/Cw5nG1/1

标签: javaregex

解决方案


我认为您需要几种解决方案。我认为需要一些不同的正则表达式。这是一个RegEx,它将有助于进一步的发展。

(\d+).*?(\b\d+\b).*?(\b\d+)

演示:https ://regex101.com/r/iIlLLN/1


推荐阅读