Domanda

Sto cercando di scrivere un espressione regolare per abbinare e dividere una sintassi variabile personalizzata in C #. L'idea qui è una formattazione personalizzata di valori stringa molto simile al String.Format / {0} stile .NET di formattazione di stringhe.

Ad esempio l'utente potrebbe definire un formato stringa da valutare in fase di esecuzione in questo modo:

D:\Path\{LanguageId}\{PersonId}\ 

Il valore 'LanguageID' corrisponde a un campo di oggetto dati, e il suo valore corrente sostituisce.

Le cose si fanno difficili quando v'è la necessità di passare argomenti al campo di formattazione. Ad esempio:

{LanguageId:English|Spanish|French}

Ciò avrebbe il significato di eseguire una logica condizionale se il valore di 'LanguageID' stato pari a uno degli argomenti.

Infine avrei bisogno di sostenere mappa argomenti come questo:

{LanguageId:English=>D:\path\english.xml|Spanish=>D:\path\spansih.xml}

Ecco un'enumerazione di tutti i possibili valori:

Comando alcun argomento : fare qualcosa di speciale

{@Date}

Comando unico argomento:

{@Date:yyyy-mm-dd}

Nessun argomento:

{LanguageId}

unico argomento-lista:

{LanguageId:English}

Multi Argument-list:

{LanguageId:English|Spanish}

unico argomento-map:

{LanguageId:English=>D:\path\english.xml}

Multi-map Argomento:

{LanguageId:English=>D:\path\english.xml|Spanish=>D:\path\spansih.xml}

Sommario:. La sintassi può essere riassunta in una chiave con optional elenco tipo di parametro o una mappa (non entrambi)

Di seguito è riportato il Regex che ho finora, che ha qualche problema, vale a dire doesnt gestire tutti gli spazi in modo corretto, in .NET io non ottenere le spaccature che mi aspetto. Per esempio nel primo esempio sto tornato una singola partita in '{LanguageID} {} PersonId' invece di due partite distinte. Anche io sono sicuro che si pretende di gestire il percorso del file system, o delimitate, stringhe tra virgolette. Qualsiasi aiuto me ottenere oltre la gobba sarebbe apprezzato. O eventuali raccomandazioni.

    private const string RegexMatch = @"
        \{                              # opening curly brace
        [\s]*                           # whitespace before command
        @?                              # command indicator
        (.[^\}\|])+                       # string characters represening command or metadata
        (                               # begin grouping of params
        :                               # required param separater 
        (                               # begin select list param type

        (                               # begin group of list param type
        .+[^\}\|]                       # string of characters for the list item
        (\|.+[^\}\|])*                  # optional multiple list items with separator
        )                               # end select list param type

        |                               # or select map param type

        (                               # begin group of map param type
        .+[^\}\|]=>.+[^\}\|]            # string of characters for map key=>value pair
        (\|.+[^\}\|]=>.+[^\}\|])*       # optional multiple param map items
        )                               # end group map param type

        )                               # end select map param type
        )                               # end grouping of params
        ?                               # allow at most 1 param group
        \s*
        \}                              # closing curly brace
        ";
È stato utile?

Soluzione

Stai cercando di fare troppo con un'espressione regolare. Vi suggerisco di rompere il compito in fasi, la prima è una semplice partita in qualcosa che assomiglia a una variabile. Che regex potrebbe essere semplice come:

\{\s*([^{}]+?)\s*\}

che salva il vostro intero variabile / stringa di comando nel gruppo # 1, meno le parentesi graffe e spazi che lo circondano. Dopo di che è possibile dividere in due punti, quindi i tubi, poi "=>" sequenze come appropriato. Non comprimere tutta la complessità in una regex mostro; se mai riesce a ottenere il regex scritto, troverete impossibile mantenere quando i requisiti cambiano in seguito.

E un'altra cosa: in questo momento, sei concentrato su come ottenere il codice per lavorare quando l'ingresso è corretto, ma che dire quando gli utenti sbagliati? Non ti piacerebbe dare loro un feedback utile? Regex succhiano a questo; stanno rigorosamente Pass / Fail. Espressioni regolari possono essere incredibilmente utile, ma come ogni altro strumento, è necessario imparare le loro limitazioni prima di poter sfruttare il loro pieno potere.

Altri suggerimenti

Si consiglia di dare un'occhiata in applicazione del presente come una macchina Finate-Stato invece di un'espressione regolare, soprattutto per puropses velocità. http://en.wikipedia.org/wiki/Finite-state_machine

Edit: In realtà, per essere precisi, si vuole guardare le macchine a stati finiti deterministico: http : //en.wikipedia.org/wiki/Deterministic_finite-state_machine

Questa realtà dovrebbe essere analizzato.

Per un esempio, ho voluto analizzare questo utilizzando Regexp::Grammars .

scusate la lunghezza.

#! /opt/perl/bin/perl
use strict;
use warnings;
use 5.10.1;

use Regexp::Grammars;

my $grammar = qr{
  ^<Path>$

  <objtoken: My::Path>
    <drive=([a-zA-Z])>:\\ <[elements=PathElement]> ** (\\) \\?

  <rule: PathElement>
    (?:
      <MATCH=BlockPathElement>
    |
      <MATCH=SimplePathElement>
    )

  <token: SimplePathElement>
    (?<= \\ ) <MATCH=([^\\]+)>

  <rule: My::BlockPathElement>
    (?<=\\){ \s*
    (?|
      <MATCH=Command>
    |
      <MATCH=Variable>
    )
    \s* }

  <objrule: My::Variable>
    <name=(\w++)> <options=VariableOptionList>?

  <rule: VariableOptionList>
      :
      <[MATCH=VariableOptionItem]> ** ([|])

  <token: VariableOptionItem>
    (?:
      <MATCH=VariableOptionMap>
    |
      <MATCH=( [^{}|]+? )>
    )

  <objrule: My::VariableOptionMap>
    \s*
    <name=(\w++)> => <value=([^{}|]+?)>
    \s*

  <objrule: My::Command>
    @ <name=(\w++)>
    (?:
      : <[arg=CommandArg]> ** ([|])
    )?

  <token: CommandArg>
    <MATCH=([^{}|]+?)> \s*

}x;

Test con:

use YAML;
while( my $line = <> ){
  chomp $line;
  local %/;

  if( $line =~ $grammar ){
    say Dump \%/;
  }else{
    die "Error: $line\n";
  }
}

Con i dati di esempio:

D:\Path\{LanguageId}\{PersonId}
E:\{ LanguageId : English | Spanish | French }
F:\Some Thing\{ LanguageId : English => D:\path\english.xml | Spanish => D:\path\spanish.xml }
C:\{@command}
c:\{@command :arg}
c:\{ @command : arg1 | arg2 }

Risultati in:

---
'': 'D:\Path\{LanguageId}\{PersonId}'
Path: !!perl/hash:My::Path
  '': 'D:\Path\{LanguageId}\{PersonId}'
  drive: D
  elements:
    - Path
    - !!perl/hash:My::Variable
      '': LanguageId
      name: LanguageId
    - !!perl/hash:My::Variable
      '': PersonId
      name: PersonId

---
'': 'E:\{ LanguageId : English | Spanish | French }'
Path: !!perl/hash:My::Path
  '': 'E:\{ LanguageId : English | Spanish | French }'
  drive: E
  elements:
    - !!perl/hash:My::Variable
      '': 'LanguageId : English | Spanish | French'
      name: LanguageId
      options:
        - English
        - Spanish
        - French

---
'': 'F:\Some Thing\{ LanguageId : English => D:\path\english.xml | Spanish => D:\path\spanish.xml }'
Path: !!perl/hash:My::Path
  '': 'F:\Some Thing\{ LanguageId : English => D:\path\english.xml | Spanish => D:\path\spanish.xml }'
  drive: F
  elements:
    - Some Thing
    - !!perl/hash:My::Variable
      '': 'LanguageId : English => D:\path\english.xml | Spanish => D:\path\spanish.xml '
      name: LanguageId
      options:
        - !!perl/hash:My::VariableOptionMap
          '': 'English => D:\path\english.xml '
          name: English
          value: D:\path\english.xml
        - !!perl/hash:My::VariableOptionMap
          '': 'Spanish => D:\path\spanish.xml '
          name: Spanish
          value: D:\path\spanish.xml

---
'': 'C:\{@command}'
Path: !!perl/hash:My::Path
  '': 'C:\{@command}'
  drive: C
  elements:
    - !!perl/hash:My::Command
      '': '@command'
      name: command

---
'': 'c:\{@command :arg}'
Path: !!perl/hash:My::Path
  '': 'c:\{@command :arg}'
  drive: c
  elements:
    - !!perl/hash:My::Command
      '': '@command :arg'
      arg:
        - arg
      name: command

---
'': 'c:\{ @command : arg1 | arg2 }'
Path: !!perl/hash:My::Path
  '': 'c:\{ @command : arg1 | arg2 }'
  drive: c
  elements:
    - !!perl/hash:My::Command
      '': '@command : arg1 | arg2 '
      arg:
        - arg1
        - arg2
      name: command

Esempio di programma:

my %ARGS = qw'
  LanguageId  English
  PersonId    someone
';

while( my $line = <> ){
  chomp $line;
  local %/;

  if( $line =~ $grammar ){
    say $/{Path}->fill( %ARGS );
  }else{
    say 'Error: ', $line;
  }
}

{
  package My::Path;

  sub fill{
    my($self,%args) = @_;

    my $out = $self->{drive}.':';

    for my $element ( @{ $self->{elements} } ){
      if( ref $element ){
        $out .= '\\' . $element->fill(%args);
      }else{
        $out .= "\\$element";
      }
    }

    return $out;
  }
}
{
  package My::Variable;

  sub fill{
    my($self,%args) = @_;

    my $name = $self->{name};

    if( exists $args{$name} ){
      $self->_fill( $args{$name} );
    }else{
      my $lc_name = lc $name;

      my @possible = grep {
        lc $_ eq $lc_name
      } keys %args;

      die qq'Cannot find argument for variable "$name"\n' unless @possible;
      if( @possible > 1 ){
        my $die = qq'Cannot determine which argument matches "$name" closer:\n';
        for my $possible( @possible ){
          $die .= qq'  "$possible"\n';
        }
        die $die;
      }

      $self->_fill( $args{$possible[1]} );
    }
  }
  sub _fill{
    my($self,$opt) = @_;

    # This is just an example.
    unless( exists $self->{options} ){
      return $opt;
    }

    for my $element ( @{$self->{options}} ){
      if( ref $element ){
        return '['.$element->value.']' if lc $element->name eq lc $opt;
      }elsif( lc $element eq lc $opt ){
        return $opt;
      }
    }

    my $name = $self->{name};
    my $die = qq'Invalid argument "$opt" for "$name" :\n';
    for my $valid ( @{$self->{options}} ){
      $die .= qq'  "$valid"\n';
    }
    die $die;
  }
}
{
  package My::VariableOptionMap;

  sub name{
    my($self) = @_;

    return $self->{name};
  }
}
{
  package My::Command;

  sub fill{
    my($self,%args) = @_;

    return '['.$self->{''}.']';
  }
}
{
  package My::VariableOptionMap;

  sub name{
    my($self) = @_;
    return $self->{name};
  }

  sub value{
    my($self) = @_;
    return $self->{value};
  }
}

Output utilizzando i dati di esempio:

D:\Path\English\someone
E:\English
F:\Some Thing\[D:\path\english.xml]
C:\[@command]
c:\[@command :arg]
c:\[@command : arg1 | arg2 ]
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top