1
votes

Java Regex obtient tous les nombres

J'ai besoin de récupérer tous les nombres d'une chaîne, exemple:

(?<=\D)(?=\d)|(?<=\d)(?=\D)

Je veux obtenir ce résultat:

  • 1
  • 2
  • 3.2
  • 4,2

Donc, je ne sais pas comment dire ça dans Regex sur Java.

En fait, j'ai ceci:

"a: 1 | b=2 ; c=3.2 / d=4,2"

Il a divisé lettre et chiffre (mais la valeur double n'est pas respectée), et le résultat est:

  • 1
  • 2
  • 3
  • 2 (problème)
  • 4
  • 2 (problème)

Pouvez-vous m'aider?

Merci: D


1 commentaires

Pouvez-vous partager le code?


4 Réponses :


2
votes

Vous pouvez utiliser un groupe de capture avec une classe de caractères :

1
2
3.2
4,2

  • [a-z] Limite de mot, correspond à un caractère a-z
  • [: =] Correspond à : ou =
  • \ h * Correspond à 0+ caractères d'espacement horizontal
  • ( Capturer le groupe 1
    • \ d + (?: [.,] \ d +)? Faites correspondre 1+ chiffres avec une partie décimale facultative avec . ou , code >
  • ) Fermer le groupe

Démo Regex | Démo Java

Par exemple

String regex = "[a-z][:=]\\h*(\\d+(?:[.,]\\d+)?)";
String string = "a: 1 | b=2 ; c=3.2 / d=4,2";

Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println(matcher.group(1));
}

Sortie

[a-z][:=]\h*(\d+(?:[.,]\d+)?)


2 commentaires

En fait, voici le résultat: [ | ,; , /,]: /


++ mais vous pouvez supprimer le \\ b de départ



0
votes

Vous pouvez jsut avoir besoin d'une expression régulière comme (\ d (?: [.,] \ d)?) que

  • trouver un chiffre
  • éventuellement point / virgule + autre chiffre après

La version à plusieurs chiffres est (\d+(?:[.,[.,.,.) )?)

String value = "a: 1 | b=2 ; c=3.2 / d=4,2";
Pattern p = Pattern.compile("(\\d(?:[.,]\\d)?)");
Matcher m = p.matcher(value);
while (m.find()) {
    System.out.println(m.group());
}
//        1
//        2
//        3.2
//        4,2

p >


0 commentaires

1
votes

Vous pouvez utiliser

/\d+(?:[.,]\d+)?/g

démo


0 commentaires

1
votes

Vous pouvez le faire comme suit:

1
2
3.2
4,2

Sortie:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) throws InterruptedException {
        // Test
        String s = "a: 1 | b=2 ; c=3.2 / d=4,2";
        showNumbers(s);
    }

    static void showNumbers(String s) {
        Pattern regex = Pattern.compile("\\d[\\d,.]*");
        Matcher matcher = regex.matcher(s);
        while (matcher.find()) {
            System.out.println(matcher.group());
        }
    }
}


0 commentaires