简体   繁体   中英

Using Regex Pattern and Matcher to print out number once only

This piece of code is part of my programme and I am trying to print out the last integer value of the string only whenever the operator and the equals sign are together (eg ^=, *=, etc.).

Hence, if I enter 4 4 ^ 4 ^ 4 ^= , I would only want to print out "4". The same counts if the number 4 is directly before the "^=", eg 4 4 ^ 4 ^ 4^=.

My code is this:

if ((input.endsWith("^=")) | (input.endsWith("*=")) |
    (input.endsWith("+=")) | (input.endsWith("-=")) |
    (input.endsWith("%=")) | (input.endsWith("/=")))
{
    Pattern p = Pattern.compile("[^\\d]*[\\d]+[^\\d]+([\\d]+)");
    Matcher m = p.matcher(input);
    if (m.find()) {
        System.out.println(m.group(1)); // second matched digits
    }
}

Currently my code prints out the number 4 multiple times, but I would only want to print it once. Any help is is appreciate.

Thank you!

You might use:

([0-9]+)\h*[\^+%/*-]=(?!.*[\^+%/*-]=)
  • ([0-9]+) Capture 1+ digits 0-9 in group 1
  • \\h* Match 0+ horizontal whitespace chars
  • [\\^+%/*-]= Match any of the listed followed by =
  • (?!.*[\\^+%/*-]=) Negative lookahead, assert what is on the right does not contain an operator followed by an equals sign

Regex demo | Java demo

In Java

final String regex = "([0-9]+)\\h*[\\^+%/*-]=(?!.*[\\^+%/*-]=)";

Try

(\d+)\s*[-+*/^%]=$
  • Find 1 or more digits and capture them
  • if they're followed by 0 or more spaces
  • followed by -, +, *, /, ^ or %
  • followed by =
  • followed by the end of the string

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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