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
startsWith method. Regexes are overkill here. For example
is true, as desired.
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.
- Within a regex the way to check for something at the beginning of a string is
- The other, simpler way to check if a string starts with something is to use
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