Skip to content
Advertisement

How to parse certain numbers from a string using regex? [closed]

i had an assignment where i have to parse certain numbers from a string in this fashion,

if I pass this string to a method the following strings for example:

*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.

it should print Edition: 32, pages from 214 to 443

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

it should print Edition: 87, pages from 104 to 105

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

it should print Edition: 10, pages from 259 to 271

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

it should print Edition: 5, pages from 1 to 4

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

it should print Edition: 8, pages from 325 to 362

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

solution

what i wrote in my solution

  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;
  }

link to Regex101 with the required sentences https://regex101.com/r/Cw5nG1/1

Advertisement

Answer

I’m not 100% clear on what are you trying to do but here is a crude approach to your problem just until you get a better solution.

getEdition method

  static String getEdition(String string) {
    var edition = "";
    Pattern ptr = Pattern.compile("w+?(?=[(])|d+?(?=[,]s)");
    Matcher match = ptr.matcher(string);
    while (match.find()) edition = match.group();
    return edition;
  }

getPages method

  static List<String> getPages(String string) {
    List<String> pages = new ArrayList<>();
    Pattern ptr = Pattern.compile("([0-9]*?)(?:-)([0-9]*?)(?=[.]|$)");
    Matcher match = ptr.matcher(string);
    if (matcher.find()) {
      pages.add(matcher.group(1));
      pages.add(matcher.group(2));
    }
    return pages;
  }
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement