Paras
Paras

Reputation: 3235

Need a way to print out lookahead portion of a regex pattern in java?


    String test = page;
    Pattern p = Pattern.compile("^\\W+\\s(?=\\w+)");
    Matcher m = p.matcher(test);
    while(m.find())
         System.out.println(m.group());

page string looks something like below:


Interest
Unknown Unknown’s 
I do not own or know of any assets that should be listed in this category.
$125
Net value of all Home property (Schedules A through H)
$128
Net value of all Bank property (Schedule I)
$253
Net value of all property (Schedules A through I)

I need to store last value lets say 253 how to find it using regex and then save it in a string.

Upvotes: 0

Views: 258

Answers (2)

Melih Altıntaş
Melih Altıntaş

Reputation: 2535

    String s = "Interest\n"
            + "Unknown Unknown’s \n"
            + "I do not own or know of any assets that should be listed in this category.\n"
            + "$125\n"
            + "Net value of all Home property (Schedules A through H)\n"
            + "$128\n"
            + "Net value of all Bank property (Schedule I)\n"
            + "$253\n"
            + "Net value of all property (Schedules A through I)";
    Pattern p = Pattern.compile("(?<=\\$)\\d+");
    Matcher m = p.matcher(s);
    while (m.find()) {
        System.out.println(m.group());
    }

output :

125 128 253

Upvotes: 2

Jesko R.
Jesko R.

Reputation: 827

It seems that what you are asking for is to find the lines containing "$125","$128","$253", etc. and you are only interested in the numbers.

In general, use grouping e.g. (\w+) to extract values not look-ahead.

Try this pattern if the value is always at the beginning of a line:

Pattern p = Pattern.compile("^\\$(\\d+)");

Upvotes: 0

Related Questions