Reputation: 477
I wish to convert my re.findall(regex) to java. I know how to use the match and pattern but I will have to compile it many times when I have multiple regex pattern to find. For example;
text = "-3-testing"
text_temp = re.findall("(.?\d+.)",text) # here one time
if len(text_temp) != 0:
if "-" in text_temp[0]:
text_temp = re.findall("(\d+.\d+)", text) #here second time
above is my python code, but if I wanted to convert to java then it means I will need to compile it 2 times and then match it again with the text and then reextract those matches. I wanted to know whether is there a more shorter way of doing it?
Upvotes: 0
Views: 300
Reputation: 1774
I think you have answered your question in your question - unless I am missing something.
Pattern p = Pattern.compile("your regex");
Then you can use the methods of Pattern as needed. You can compile as many patterns as you like and use them to generate as many matchers as you can handle.
For example:
Matcher m = p.matcher("some input");
And from there you can use the Matcher to do all your extraction of data, stepping through matches, replacements and so on...
As for having multiple patterns, you will need to compile each pattern unless you can combine them IInto one. Perhaps by using the "alternatives" operator "|" or having a more generic (or more specific) pattern. Which gives rise to the question, why would you regex something generic only to constrain it more in another step?
Perhaps you could do something like this and have just one?
Pattern p = Pattern.compile("-(\d+.\d+)");
Upvotes: 1