Domanda

Come faccio a fare questo con regex?

voglio abbinare questa stringa: -myString

ma io non voglio che corrisponda al -myString in questa stringa: --myString

myString è ovviamente nulla.

È anche possibile?

EDIT:

qui è un po 'più di informazioni con quello che ho ottenuto finora da quando ho postato una domanda:

string to match:
some random stuff here -string1, --string2, other stuff here
regex:
(-)([\w])*

Questa espressione regolare mi riporta 3 partite: -string1, - e -string2

Idealmente mi piacerebbe a me restituire solo il match -string1

È stato utile?

Soluzione

Supponendo vostri supporti motore regex (negativi) lookbehind:

/(?<!-)-myString/

Perl fa, Javascript non lo fa, per esempio.

Altri suggerimenti

Si vuole abbinare una stringa che inizia con un singolo trattino, ma non uno che ha più trattini?

^-[^-]

Spiegazione:

^ Matches start of string
- Matches a dash
[^-] Matches anything but a dash
/^[^-]*-myString/

Test:

[~]$ echo -myString | egrep -e '^[^-]*-myString'
-myString
[~]$ echo --myString | egrep -e '^[^-]*-myString'
[~]$ echo test--myString | egrep -e '^[^-]*-myString'
[~]$ echo test --myString | egrep -e '^[^-]*-myString'
[~]$ echo test -myString | egrep -e '^[^-]*-myString'
test -myString

in base alla ultima modifica, immagino la seguente espressione avrebbe funzionato meglio

\b\-\w+
  

[^ -] {0,1} - [^ \ w -] +

senza l'utilizzo di look-sedere, uso:

(?:^|(?:[\s,]))(?:\-)([^-][a-zA-Z_0-9]+)

rotto out:

(
  ?:^|(?:[\s,])        # Determine if this is at the beginning of the input,
                       # or is preceded by whitespace or a comma
)
(
  ?:\-                 # Check for the first dash
)
(
  [^-][a-zA-Z_0-9]+    # Capture a string that doesn't start with a dash
                       # (the string you are looking for)
)
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top