简体   繁体   中英

To regex with a string or to not regex with a string?

I've started using the .match(Regex) method in my java program, but for now I'm just using a string ( String regexString = new String("[^a-zA-Z0-9][^a-zA-Z0-9]*"); which is what I have so far, as an example). I know however I can use an actual regex ( Regex pattern = new Regex() & the Pattern class then compile it (?) some how).

Is there an advantage to using Regex as a class and not just a string, in java? I'm quite used to bash scripting and there regexes are just 'strings' in the loosest sense, and there is no ability/need for a separate class, so I'm struggling to see where there is one here.

I would do what you think is simplest and clearest.

A Pattern is often used when the performance of a regex is critical. If you haven't profiled your application and it has been shown to be an issue, using a plain String is likely to be fine.

The regular expression you are trying to use for matching purposes must be transformed in a finit state machine that accepts any text that matches the pattern you provided.

Thus, every time you use a regular expression, for example in the (new String("").split("") expression, a pattern is constructed in the background, namely a finite state machine, which receives the sequence of characters in your string and tries to match the input.

If you have a regular expression that you use often and speed is a real concern, then keeping the finite state machine and not constructing it every time is an important speedup. You can do so by storing the Pattern object between successive calls of match onn different output strings.

The following should provide some more insight: http://en.wikipedia.org/wiki/Finite-state_machine

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM