Ho una stringa %/O^/O%/O
. Voglio trovare l'ultimo/dividere la stringa. Il primo tentativo è stato: \/[POL]$
ma questo ha compreso lo "O"
che è ovvio. Qualcuno ha un suggerimento?Trova l'ultimo indice di Regex in Java
risposta
Avete bisogno di usare le espressioni regolari per questo? Sarebbe String. lastIndexOf("/") funziona per trovare l'indice e quindi usa String.substring(int start, int end) con il risultato? O i tuoi dati effettivi sono diversi e più complicati, richiedendo espressioni regolari? Con quello che hai fornito a dividere la stringa sull'ultimo /, ecco il codice:
int lastSlash = mystring.lastIndexOf("/");
String start = mystring.substring(0, lastSlash);
String end = mystring.substring(lastSlash + 1, mystring.length);
/(?=[^/]*$)
corrisponderà un /
che non è seguito da alcun più /
s. Per dividere su di esso, utilizzare
String[] splitArray = subjectString.split("/(?=[^/]*$)");
Se invece si è interessati per trovare l'ultima istanza di un'espressione regolare carattere è eccessivo, si deve solo usare lastIndexOf di String
int pos = myString.lastIndexOf('/');
+1 - questo è più efficiente. D'altra parte, una regex che trova l'ultimo '/' può essere inserita direttamente in '.split()' - è probabilmente il gusto personale di quale sia più leggibile (confronta la mia soluzione con quella di justkt). –
La questione centrale è buono anche se l'esempio che ha dato non si bisogno. IndexOf di Java non accetta espressioni regolari. Rispondere parte solo oggetto della questione, ecco che cosa si avrebbe bisogno:
/**
* Version of indexOf that uses regular expressions for the search
* by Julian Cochran.
*/
public static int indexOfRegex(String message, String toFind) {
// Need to add an extra character to message because to ensure
// split works if toFind is right at the end of the message.
message = message + " ";
String separated[] = message.split(toFind);
if (separated == null ||
separated.length == 0 ||
separated.length == 1) {
return -1;
}
return separated[0].length();
}
Se è necessario l'ultimo indice:
/**
* Version of lastIndexOf that uses regular expressions for
* the search by Julian Cochran.
*/
public static int lastIndexOfRegex(String message, String toFind) {
// Need to add an extra character to message because to ensure
// split works if toFind is right at the end of the message.
message = message + " ";
String separated[] = message.split(toFind);
if (separated == null ||
separated.length == 0 ||
separated.length == 1) {
return -1;
}
return separated[separated.length - 1].length();
}
Questo mi è stato utile. –
@ Julian Cochran. Ho comprato un libro usato e ha il tuo nome e un'immagine di te e tua figlia e tuo figlio? Se tu mi piacerebbe avere l'immagine per te. Ci scusiamo per il rumore sentire SE, ma nessun altro modo per trovare ... – clg4
Sono d'accordo che usando il metodo standard String.lastIndexOf() è la vostra la migliore linea d'azione, ma di recente ho usato la parte Regex (ovvero, volevo trovare l'ultimo carattere non alfanumerico in una stringa).
ho finito per scrivere io stesso, e ho pensato di condividere, nella speranza che sarebbe servito per aiutare gli altri:
/**
* Indicates that a String search operation yielded no results.
*/
public static final int NOT_FOUND = -1;
/**
* Version of lastIndexOf that uses regular expressions for searching.
* By Tomer Godinger.
*
* @param str String in which to search for the pattern.
* @param toFind Pattern to locate.
* @return The index of the requested pattern, if found; NOT_FOUND (-1) otherwise.
*/
public static int lastIndexOfRegex(String str, String toFind)
{
Pattern pattern = Pattern.compile(toFind);
Matcher matcher = pattern.matcher(str);
// Default to the NOT_FOUND constant
int lastIndex = NOT_FOUND;
// Search for the given pattern
while (matcher.find())
{
lastIndex = matcher.start();
}
return lastIndex;
}
/**
* Finds the last index of the given regular expression pattern in the given string,
* starting from the given index (and conceptually going backwards).
* By Tomer Godinger.
*
* @param str String in which to search for the pattern.
* @param toFind Pattern to locate.
* @param fromIndex Maximum allowed index.
* @return The index of the requested pattern, if found; NOT_FOUND (-1) otherwise.
*/
public static int lastIndexOfRegex(String str, String toFind, int fromIndex)
{
// Limit the search by searching on a suitable substring
return lastIndexOfRegex(str.substring(0, fromIndex), toFind);
}
Inoltre, può essere possibile per rendere questo metodo più veloce prima invertendo la stringa di input , quindi prendendo l'indice finale del primo gruppo (piuttosto che andare su tutti i gruppi).
Ma per farlo bisognerebbe invertire anche il modello; in alcuni casi può essere semplice (come nel mio caso di ricerca di un singolo personaggio), ma può rivelarsi problematico in altri.
String name ="rami is good boy, and he is working for andorid,is completed";
int lastSlash = name.lastIndexOf("is");
String start = name.substring(0, lastSlash);
String end = name.substring(lastSlash + 1, name.length());
StringBuffer sb = new StringBuffer(name);
sb.replace(start.length(), name.lastIndexOf(end)+1, "");
System.out.println(sb.toString());
ref: https://github.com/apache/commons-lang/pull/273/files
public static int lastIndexOfAnyChar(final CharSequence str,final String searchChars) {
return searchChars == null ? INDEX_NOT_FOUND : lastIndexOfAnyChar(str,searchChars.toCharArray());
}
/**
* <p>Search a CharSequence to find the last index of any
* character in the given set of characters.</p>
*
* <p>A {@code null} String will return {@code -1}.
* A {@code null} or zero length search array will return {@code -1}.</p>
*
* <pre>
* StringUtils.lastIndexOfAnyChar(null, *) = -1
* StringUtils.lastIndexOfAnyChar("", *) = -1
* StringUtils.lastIndexOfAnyChar(*, null) = -1
* StringUtils.lastIndexOfAnyChar(*, []) = -1
* StringUtils.lastIndexOfAnyChar("zzabyycdxx",['z','a']) = 2
* StringUtils.lastIndexOfAnyChar("zzabyycdxx",['b','y']) = 5
* StringUtils.lastIndexOfAnyChar("aba", ['z']) = -1
* </pre>
*
* @param cs the CharSequence to check, may be null
* @param searchChars the chars to search for, may be null
* @return the last index of any of the chars, -1 if no match or null input
*/
public static int lastIndexOfAnyChar(final CharSequence str,final char... searchChars) {
if (isEmpty(str) || ArrayUtils.isEmpty(searchChars)) {
return INDEX_NOT_FOUND;
}
int csLen = str.length();
int csLast = csLen - 1;
int searchLen = searchChars.length;
int searchLast = searchLen - 1;
for (int i = csLast ; i >= 0 ; i--) {
char ch = str.charAt(i);
for (int j = 0; j < searchLen; j++) {
if (searchChars[j] == ch) {
if (i < csLast && j < searchLast && Character.isHighSurrogate(ch)) {
// ch is a supplementary character
if (searchChars[j + 1] == str.charAt(i + 1)) {
return i;
}
} else {
return i;
}
}
}
}
return INDEX_NOT_FOUND;
}
- 1. Trova l'ultimo indice di "\" in una stringa in java
- 2. Trova indice TabStrip
- 3. Indice di riferimento della libreria Regex
- 4. Trova il primo indice di una stringa dopo indice
- 5. Trova figlio per indice jQuery
- 6. jquery trova per indice in un elenco
- 7. punteggiatura Regex in Java
- 8. Simple Python Regex Trova modello
- 9. Trova indice nella matrice di oggetti
- 10. Trova l'indirizzo di un indice in un array in C
- 11. regex: trova il numero di una cifra
- 12. Trova sine in Java
- 13. Indice Bounds su Mongo Regex Ricerca
- 14. Python - trova indice intero di righe con NaN in panda
- 15. Trova l'ultimo indice di un carattere in una stringa
- 16. Corrispondenza '_' e '-' in java regex
- 17. Java: suddivisione di un testo utilizzando Regex
- 18. Java e lookbehind in regex
- 19. Stampa regex partite in java
- 20. Trova partita su array di RegEx in MongoDB Collection
- 21. Delphi - trova carattere una data posizione/indice
- 22. Trova indice riga tabella utilizzando jQuery
- 23. partite di lunghezza zero in Java Regex
- 24. Java: sottostringa gamma indice
- 25. Visual Studio, Trova e sostituisci, regex
- 26. Javascript regex: Trova tutti gli URL ottimizzazione
- 27. Regex trova la parola nella stringa
- 28. Perl regex trova carattere da set arbitrario
- 29. Come convertire javascript regex in regex java sicuro?
- 30. Spiegare regex che trova i commenti CSS
Questa dovrebbe essere la risposta accettata. –