Extract matching string using reg-ex

I searched for Java regex issues and found out about the Pattern and Matcher classes so that you get a group of text around reg-ex matching criteria.

However, my requirement is different. I want to extract the actual text represented by a regular expression.

Example:

Input text: ABC 22. XYZ
Regular expression: (.*) [0-9]* (.*)

Using the Pattern and Matcher classes (or any other method in Java), how can I get the text "22."? This is the text that represents the regular expression.

+4
source share
3 answers

Your capture groups are disabled.

Pattern p = Pattern.compile ("(\\d+\\.?)");
Matcher m = p.matcher ("ABC 22. XYZ");
if (m.find ()) {
  System.out.println  (m.group (1));
}

( ) , . 0 - .

0

1:

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

2 , , :

Imgur

, Java - :

String input = "ABC 22. XYZ";

System.out.println(
    input.replaceAll(".*?(\\s*\\d+\\.\\s+).*", "$1")
);  // prints " 22. "

$1 group #1.


  • :

    NODE         EXPLANATION
    ------------------------------------------------------------------
      .*?        any character except \n (0 or more times
                 (matching the least amount possible))
    ------------------------------------------------------------------
      (          group and capture to \1:
    ------------------------------------------------------------------
        \s*        whitespace (\n, \r, \t, \f, and " ") (0
                   or more times (matching the most amount
                   possible))
    ------------------------------------------------------------------
        \d+        digits (0-9) (1 or more times (matching
                   the most amount possible))
    ------------------------------------------------------------------
        \.         '.'
    ------------------------------------------------------------------
        \s+        whitespace (\n, \r, \t, \f, and " ") (1
                   or more times (matching the most amount
                   possible))
    ------------------------------------------------------------------
      )          end of \1
    ------------------------------------------------------------------
      .*         any character except \n (0 or more times
                 (matching the most amount possible))
    
  • , , Regexper.

+1

"22", .

, :

String number = input.replaceAll(".*?(\\d+).*", "$1");

This regular expression matches the (first) number (of any length) anywhere in the entry, regardless of the rest of the input.

0
source

Source: https://habr.com/ru/post/1622437/


All Articles