Ayuda de autocompletado difuso de expresiones regulares

Trying to write a regular expression for java that will return true ONLY if the term is included @ the beginning of the string (to be used for an auto-complete). So if my term was 'work' I would want it to return false for 'homework' but true for 'workers'. Even the term 'wo' should be true for 'workers'. Can anyone help? Any info much appreciated.

Also not sure if it matters, they might have these special characters as part of the auto complete term (, ), -, ., :, /, _, and spaces.

preguntado el 27 de agosto de 11 a las 20:08

4 Respuestas

Utiliza startsWith method. Regexes are overkill here. For example

"workers".startsWith("wo")

is true, as desired.

Respondido 28 ago 11, 00:08

Its funny I found this just before you posted =). Thanks! - BZB

There are a few different approaches here, but to be honest I'm not sure a regular expression is the right one. You haven't given us anything in the way of code so far, so all I can give you is some hints.

  1. Within a regex the way to check for something at the beginning of a string is ^.
  2. The other, simpler way to check if a string starts with something is to use startsWith.

Respondido 28 ago 11, 00:08

If you only want to match prefixes you are better off not using regular expressions. Naively you could just the the String.startsWith method and it would be much faster than a similar regular expression.

an even faster option would be to use a Trie here is a sample implementation: http://www.cs.duke.edu/~ola/courses/cps108/fall96/joggle/trie/Trie.java

Respondido 28 ago 11, 00:08

¿Por qué no lo haces? term.startsWith(start)?

Respondido 28 ago 11, 00:08

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.