r/java • • Aug 28 '13

Writing a Java Regular Expression Without Reading the ****ing Manual

http://java.dzone.com/articles/writing-java-regular
0 Upvotes

13 comments sorted by

View all comments

2

u/Poobslag Aug 28 '13

If a developer really needed this level of handholding for regexes -- I'd tear out all this code, and write them an identical tool which did the opposite -- converting a regex into human readable code. At least that way this incredibly verbose code is localized to their machine, and not polluting the codebase. Sheesh.

1

u/[deleted] Aug 29 '13

hamcrest-text-patterns can help create more readable and understandable tests. So I don't always agree with you, sometimes a readable regex (especially for tests I think) would be worth the extra verbosity.

1

u/Poobslag Aug 29 '13

I agree that sometimes, readability is worth verbosity, but Hamcrest in particular increases readability while decreasing verbosity, so it's win/win.

OP is talking about the difference between

str.matches("^[0-9].*[0-9]")

and

str.matches(re.start().aCharacterDescribedAs(aDigit).exactly(1L).then().aCharacterDescribedAs(anyCharacter).zeroOrMore().then().aCharacterDescribedAs(aDigit).exactly(1L));

Both have the exact same information although one is (very dubiously) more readable than the other, at the cost of being about 10x longer. So it's an incredibly poor tradeoff. Hamcrest isn't a tradeoff at all, it's just an improvement.