IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Macros et VBA Excel Discussion :

Regex simple (strPattern = ".*([0-9.]{1,4}(kg|g)).*") ne fonctionne pas [XL-2019]


Sujet :

Macros et VBA Excel

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre éclairé

    Homme Profil pro
    Consultant informatique
    Inscrit en
    Septembre 2011
    Messages
    371
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Industrie

    Informations forums :
    Inscription : Septembre 2011
    Messages : 371
    Par défaut Regex simple (strPattern = ".*([0-9.]{1,4}(kg|g)).*") ne fonctionne pas
    Bonjour,

    dans une macro j'ai une regex qui ne me retourne pas le résultat désiré.

    strPattern = ".*([0-9.]{1,4}(kg|g)).*"

    Je cherche à récupérer le poid qui est indiqué dans une cellule.
    La cellule peut avoir les formes/valeurs suivantes:

    • zefjkh 5g fdkjh
    • sdjkmlh20gx4
    • smkljh100gsddd
    • sqlvkjh1000gvljkhgsqd
    • vslkdjh1kgvsdkjv
    • slkhjg15kg-sdfkljh
    • qsfdgkljh1.5kgsdgqg
    • qsd200kjh12.7kgdsfgkjhg


    Le probleme est que le résultat retourné est comme ceci:

    • 5g
    • 0g
    • 0g
    • 0g
    • 1kg
    • 5kg
    • 5kg
    • 7kg

    Qu'est-ce qui cloche dans la regex?

    Merci d'avance
    vandman

  2. #2
    Expert confirmé
    Avatar de jurassic pork
    Homme Profil pro
    Bidouilleur
    Inscrit en
    Décembre 2008
    Messages
    4 248
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Bidouilleur
    Secteur : Industrie

    Informations forums :
    Inscription : Décembre 2008
    Messages : 4 248
    Par défaut
    Hello,
    le souci, c'est le début de ton motif, c'est à dire .* qui signifie tous les caractères dont font partie les chiffres alors manque de chance, le calcul de l'expression régulière va aller au plus large pour cette partie, c'est à dire ne laisser qu'un chiffre dans la partie [0-9.]{1,4}
    Voici un motif qui fonctionne chez moi avec les données que tu as données :
    [^0-9]*([0-9.]{1,4}(kg|g)).*
    On utilise [^0-9]* qui signifie tous les caractères qui ne sont pas des chiffres.
    Code de test :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    Sub TestRegex()
        Dim RegEx, REMatches, Cell As Object
        Set RegEx = CreateObject("vbscript.regexp")
         With RegEx
            .Global = True
            .IgnoreCase = False
            ' Motif
            .Pattern = "[^0-9]*([0-9.]{1,4}(kg|g)).*"
         End With
        For Each Cell In Sheets("Feuil3").Range("A1:A8").Rows.Cells
        Set REMatches = RegEx.Execute(Cell.value)
        If REMatches.Count > 0 Then
          Debug.Print REMatches(0).SubMatches(0)
        End If    
        Next

    Résultat :
    5g
    20g
    100g
    1000g
    1kg
    15kg
    1.5kg
    12.7kg

    Ami calmant, J.P

  3. #3
    Membre éclairé

    Homme Profil pro
    Consultant informatique
    Inscrit en
    Septembre 2011
    Messages
    371
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Industrie

    Informations forums :
    Inscription : Septembre 2011
    Messages : 371
    Par défaut
    Bonjour et merci pour la réponse qui me fait avancer.

    J'ai un autre soucis, ca e fonctionne pas encore toujours. Peut être est-ce du au fait que la ou je suis, les caractères son Coréen. C'est la première fois que je fais une regex avec du coréen.
    La liste suivante donne comme résutat:
    백설 발효조미료2.5 1kg-1개 백설 발효조미료2.51kg
    맥선 박력2등급밀가루20kg-1개 맥선 박력220kg
    맥선 유기농밀가루 중력1등20kg 중력분-1개 맥선 유기농밀가루 중력120kg
    백설 밀가루 중력 3등A 20kg-1개 백설 밀가루 중력 320kg

    pour le reste ca fonctionne.

    PS: voisi le code
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    Function simpleCellRegex(Myrange As Range) As String
        Dim regex As New RegExp
        Dim strPattern As String
        Dim strInput As String
        Dim strReplace As String
        Dim strOutput As String
     
        strPattern = "[^0-9]*([0-9.]{1,4}(kg|g|ml|l)).*"
     
        strInput = Myrange.Value
        strReplace = "$1"
     
        With regex
            .Global = True
            .MultiLine = True
            .IgnoreCase = True
            .Pattern = strPattern
        End With
     
        If regex.Test(strInput) Then
            simpleCellRegex = regex.Replace(strInput, "$1")
        Else: simpleCellRegex = "Not matched"
        End If
    End Function

  4. #4
    Expert confirmé
    Avatar de jurassic pork
    Homme Profil pro
    Bidouilleur
    Inscrit en
    Décembre 2008
    Messages
    4 248
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Bidouilleur
    Secteur : Industrie

    Informations forums :
    Inscription : Décembre 2008
    Messages : 4 248
    Par défaut
    c'est bizarre parce qu'avec ce code :
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    Sub TestRegex()
        Dim RegEx, REMatches, Cell As Object
        Set RegEx = CreateObject("vbscript.regexp")
         With RegEx
            .Global = True
            .IgnoreCase = False
            ' Motif
            .Pattern = "[^0-9]*([0-9.]{1,4}(kg|g|ml|l)).*"
         End With
        For Each Cell In Sheets("Feuil3").Range("A1:A12").Rows.Cells
        Set REMatches = RegEx.Execute(Cell.value)
        If REMatches.Count > 0 Then
          Debug.Print REMatches(0).SubMatches(0)
          Cell.Offset(0, 1).value = REMatches(0).SubMatches(0)
        End If
        Next
     
     
    End Sub
    voici ce que j'obtiens :

    Nom : xlRegexCoreen.PNG
Affichages : 302
Taille : 18,3 Ko

    Excel 2019 - 32 bits - Windows 10 Français

    Cela doit être ton RegEx.Replace(Cell.value, "$1") qui n'est pas bon

  5. #5
    Membre éclairé

    Homme Profil pro
    Consultant informatique
    Inscrit en
    Septembre 2011
    Messages
    371
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France

    Informations professionnelles :
    Activité : Consultant informatique
    Secteur : Industrie

    Informations forums :
    Inscription : Septembre 2011
    Messages : 371
    Par défaut
    Bonjour,
    Après modification de mon code, ca fonctionne bien. Merci pour l'aide

    PS: Voici ce que ca donne au final:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
    Function calcKg(Cell As Object)
        Dim RegEx, RegEx_pkg, RegEx_exception, REMatches, REMatches_exception As Object
        Set RegEx = CreateObject("vbscript.regexp")
        Set RegEx_pkg = CreateObject("vbscript.regexp")
        Set RegEx_exception = CreateObject("vbscript.regexp")
        Dim unit, expt As String
        Dim value, pkg, exception(), item As Variant
     
        ReDim exception(15)
        exception(0) = "[^0-9]*(으뜸김240봉).*"
        exception(1) = "[^0-9]*(덴티메이트칫솔 [5+]{3}입).*"
        exception(2) = ".*(대륙식품 도시락김 240개).*"
        exception(3) = ".*(동원 반코팅 장갑 1호).*"
        exception(4) = ".*(맥선 유기농밀가루 강력분20k).*"
        exception(5) = "(맥스웰하우스 커피믹스 마일드).*"
        exception(6) = ".*(맥심 모카골드 마일드 -220T).*"
        exception(7) = ".*(면장갑 초록테 -10켤레).*"
        exception(8) = ".*(센스플러스 크린롤팩25cmx35cm 500매).*"
        exception(9) = ".*(스포롱 클리너 수세미).*"
        exception(10) = ".*(에코미 물티슈 400매).*"
        exception(11) = "(이츠웰 랩 40cmx500m).*"
        exception(12) = "(청정원 위생 크린백).*"
        exception(13) = "(14온즈 무지 아이스컵).*"
        exception(14) = "(큐원 갈색설탕).*"
        exception(15) = "(크린랩 크린장갑200매).*"
     
        With RegEx
            .Global = True
            .MultiLine = True
            .IgnoreCase = True
            .Pattern = "[^0-9]*([0-9.]{1,4}(kg|g|ml|l)).*"
        End With
     
        With RegEx_pkg
            .Global = True
            .MultiLine = True
            .IgnoreCase = True
            .Pattern = "[^0-9]*([^(][0-9]{1,4}(입)[^)]).*"
        End With
     
        Set REMatches = RegEx_pkg.Execute(Cell.value)
        If REMatches.Count > 0 Then
            pkg = CVar(Replace(REMatches(0).SubMatches(0), REMatches(0).SubMatches(1), ""))
        Else:
            pkg = 1
        End If
     
        Set REMatches = RegEx.Execute(Cell.value)
        If REMatches.Count > 0 Then
            unit = REMatches(0).SubMatches(1)
            value = CVar(Replace(REMatches(0).SubMatches(0), unit, ""))
     
            Select Case unit    ' Evaluate unit.
            Case "kg", "Kg", "KG"
                calcKg = value * pkg
            Case "g", "G"
                calcKg = (value / 1000) * pkg
            Case "ml", "mL"
            ' 1L => 1.65Kg'
                calcKg = (value / 1000) * 1.65 * pkg
            Case "l", "L"
                calcKg = value * 1.65 * pkg
            Case Else    ' Other values.
                calcKg = "Not matched"
            End Select
        Else:
            For Each item In exception
                With RegEx_exception
                    .Global = True
                    .MultiLine = True
                    .IgnoreCase = True
                    .Pattern = item
                End With
                Set REMatches_exception = RegEx_exception.Execute(Cell.value)
                If REMatches_exception.Count > 0 Then
                    expt = REMatches_exception(0).SubMatches(0)
                    Select Case expt    ' Evaluate expt.
                    Case "덴티메이트칫솔 5+5입"
                        calcKg = expt
                    Case "으뜸김240봉"
                        calcKg = expt
                    Case "대륙식품 도시락김 240개"
                        calcKg = expt
                    Case "동원 반코팅 장갑 1호"
                        calcKg = expt
                    Case "맥선 유기농밀가루 강력분20k"
                        calcKg = 20 / 1
                    Case "맥스웰하우스 커피믹스 마일드"
                        calcKg = expt
                    Case "맥심 모카골드 마일드 -220T"
                        calcKg = expt
                    Case "면장갑 초록테 -10켤레"
                        calcKg = expt
                    Case "센스플러스 크린롤팩25cmx35cm 500매"
                        calcKg = expt
                    Case "스포롱 클리너 수세미"
                        calcKg = expt
                    Case "에코미 물티슈 400매"
                        calcKg = expt
                    Case "이츠웰 랩 40cmx500m"
                        calcKg = expt
                    Case "청정원 위생 크린백"
                        calcKg = expt
                    Case "14온즈 무지 아이스컵"
                        calcKg = expt
                    Case "큐원 갈색설탕"
                        calcKg = expt
                    Case "크린랩 크린장갑200매"
                        calcKg = expt
                    Case Else
                         calcKg = "Not matched"
                    End Select
                End If
            Next item
        End If
    End Function

+ Répondre à la discussion
Cette discussion est résolue.

Discussions similaires

  1. [RegEx] Regex simple mais qui ne fonctionne pas comme il faut
    Par yagami77 dans le forum Langage
    Réponses: 1
    Dernier message: 08/01/2011, 23h27
  2. une regex simple : trouver un mot en 6 majuscules
    Par EnRadeSurEclipse dans le forum Requêtes
    Réponses: 6
    Dernier message: 21/05/2010, 15h55
  3. [RegEx] Regex simple: Verfier premier caractère d'une chaine.
    Par yann123456 dans le forum Langage
    Réponses: 2
    Dernier message: 07/04/2009, 15h50
  4. [RegEx] Regex simple qui ne fonctionne pas
    Par Bruno.C dans le forum Langage
    Réponses: 4
    Dernier message: 03/12/2008, 15h05
  5. [RegEx] regex simple qui ne marche pas (encore)
    Par denisvignes dans le forum Langage
    Réponses: 5
    Dernier message: 19/09/2008, 15h04

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo