Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

java

string

regex

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.

like image 376
AncientSwordRage Avatar asked Oct 03 '12 08:10

AncientSwordRage


People also ask

Does regex only work with strings?

So, yes, regular expressions really only apply to strings. If you want a more complicated FSM, then it's possible to write one, but not using your local regex engine.

What does '$' mean in regex?

$ means "Match the end of the string" (the position after the last character in the string).


1 Answers

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.

like image 71
Peter Lawrey Avatar answered Oct 25 '22 20:10

Peter Lawrey