Skip to content

Tag: regex

How to match any combination of letters using regex?

How can I match letters a,b,c once in any combination and varying length like this: The expression should match these cases: but should not match these ones: Answer Use regex pattern You can use this pattern with any set and size, just replace [abc] with desired set… Example: (above output is from myreg…

Use variables in pattern matcher

I have the following: But would like to replace the {6,20} with variable values due to them been dynamic in some cases. I.e. How can I include variables in the Reg Exp? Thanks Answer Use Java’s simple string concatenation, using the plus sign. Indeed, as Michael suggested compiling it is better for perf…

Canonical equivalence in Pattern

I am referring to the test harness listed here http://docs.oracle.com/javase/tutorial/essential/regex/test_harness.html The only change I made to the class is that the pattern is created as below: As the tutorial at http://docs.oracle.com/javase/tutorial/essential/regex/pattern.html suggests I put in the patt…

Regex for matching something if it is not preceded by something else

With regex in Java, I want to write a regex that will match if and only if the pattern is not preceded by certain characters. For example: I want to match if bar is not preceded by foo. So the output would be: Answer You want to use negative lookbehind like this: Where (?<!x) means “only if it doesn&…

Regex to match words of a certain length

I would like to know the regex to match words such that the words have a maximum length. for eg, if a word is of maximum 10 characters in length, I would like the regex to match, but if the length exceeds 10, then the regex should not match. I tried but that brings me matches only if the minimum

Regex doesn’t work in String.matches()

I have this small piece of code Supposed to print but it prints nothing!! Answer Welcome to Java’s misnamed .matches() method… It tries and matches ALL the input. Unfortunately, other languages have followed suit 🙁 If you want to see if the regex matches an input text, use a Pattern, a Matcher and…

Split using a bracket

How can I split a string using [ as the delimiter? if I do I get an error Exception in thread “main” java.util.regex.PatternSyntaxException: Unclosed character class near index 1 [ Any help? Answer The [ is a reserved char in regex, you need to escape it,