0

So I have these Regex Objs in JS

const itemModelRegEx = new RegExp
(/^(item1|item2|item3|item4)(-)(\d{4}((0[1-9])|(1[0-2]))(0[1-9]|[1-2][0-9]|3[0-1]))(?:.*)/, 'i',);

const dateRegex = new RegExp(/(20\d{2})([0-1]\d)([0-3]\d)/i);

currently I am trying to convert them to Java as such:

String regexOne = "^(item1|item2|item3|item4)(-)(\d{4}((0[1-9])|(1[0-2]))(0[1-9]|[1-2][0-9]|3[0-1]))(?:.*)"
Pattern itemModelRegEx = Pattern.compile(regexOne);

Pattern dateRegex = Pattern.compile("(20\d{2})([0-1]\d)([0-3]\d)");

However, this doesn't seem to be correct. What would a proper conversion here look like? Would the same wildcards apply? I removed the "/" from start and end but should the "\" in the pattern be set-up differently?

4
  • 2
    Try double escaping the backslashes Commented Nov 27, 2019 at 23:44
  • Pattern.compile("(20\\d{2})([0-1]\\d)([0-3]\\d)") like this? Commented Nov 27, 2019 at 23:52
  • Yes, did you try it out? You can write [0-1] as [01] Commented Nov 27, 2019 at 23:55
  • 1
    I don't know yet there's multiple other patterns will update once I have tested properly Commented Nov 27, 2019 at 23:56

1 Answer 1

1

Any \ or " in the regex needs to be escaped for the Java string literal.

final Pattern itemModelRegEx = Pattern.compile(
        "^(item1|item2|item3|item4)(-)(\\d{4}((0[1-9])|(1[0-2]))(0[1-9]|[1-2][0-9]|3[0-1]))(?:.*)",
        Pattern.CASE_INSENSITIVE);
final Pattern dateRegex = Pattern.compile(
        "(20\\d{2})([0-1]\\d)([0-3]\\d)",
        Pattern.CASE_INSENSITIVE);

The i flag is the CASE_INSENSITIVE flag, and can be specified separately as done in the JS code and in the Java code above. It can also be embedded in the regex itself as (?i), though specifying it for the second pattern doesn't make sense, given that it only matches digits:

final Pattern itemModelRegEx = Pattern.compile(
        "(?i)^(item1|item2|item3|item4)(-)(\\d{4}((0[1-9])|(1[0-2]))(0[1-9]|[1-2][0-9]|3[0-1]))(?:.*)");
final Pattern dateRegex = Pattern.compile(
        "(20\\d{2})([0-1]\\d)([0-3]\\d)");
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.