0

I am trying to come up with correct regex for the below usecase:

prefix.string1.anyNumber.string2.anyNumber.string3

example 1: prefix.abcd.22.pqr.55.xyz

example 2: prefix.abcd.22.xyz

example 3: prefix.pqr.55.xyz

Need to generate a regex that I can use to generate Pattern in java.

I tried the below:

String regex = "prefix\.abcd\.\d\.pqr\.\d\.xyz|prefix\.abcd\.\d\.xyz|prefix\.pqr\.\d\.xyz"
Pattern p = Pattern.compile(regex);

It does not work. I have not used patterns much before. Trying to figure out what I am missing here. Appreciate any help. Thank you.

Zack
  • 2,078
  • 10
  • 33
  • 58
  • are you using the matcher class to check if the string input matches with the regex – ibrhm117 Jun 18 '20 at 05:04
  • Do you need to match alternating string and numbers delimited by ".". Or just the given examples? – Alanpatchi Jun 18 '20 at 05:09
  • just the given examples – Zack Jun 18 '20 at 05:10
  • can you check this regex- prefix\.abcd\.F?[0-9]..pqr\..F?[0-9].xyz – Bharathiraja Jun 18 '20 at 05:11
  • Use this site to manipulate your regex - https://www.regextester.com/110436 – Bharathiraja Jun 18 '20 at 05:12
  • 6
    as your numbers contain several digits you should use "\d+" for them. and do not forget to escape \ in Java strings: `String regex = "prefix\\.abcd\\.\\d+\\.pqr\\.\\d+\\.xyz|prefix\\.abcd\\.\\d+\\.xyz|prefix\\.pqr\\.\\d+\\.xyz";` – Nowhere Man Jun 18 '20 at 05:14
  • 1
    Does [**this**](https://regex101.com/r/HFU1hw/1) help? –  Jun 18 '20 at 05:17
  • Try `prefix(?:(?:\.abcd\.22)?(?:\.pqr\.55)?|(?:\.abcd\.22))\.xyz` https://regex101.com/r/D0hOcr/1 In Java `String regex = "prefix(?:(?:\\.abcd\\.22)?(?:\\.pqr\\.55)?|(?:\\.abcd\\.22))\\.xyz";` – The fourth bird Jun 18 '20 at 05:26
  • `String regex = "prefix\\.[a-zA-Z]+\\.\\d+\\.[a-zA-Z]+(\\.\\d+\\.[a-zA-Z]+)?"`. This matches both `prefix.string.anyNumber.string` and `prefix.string.anyNumber.string.anyNumber.string`. – Alanpatchi Jun 18 '20 at 05:27
  • 1
    To make your pattern work, you have to use `\d+` and in Java double escape the backslashes. – The fourth bird Jun 18 '20 at 05:32
  • 2
    Does this answer your question? [What is the backslash character (\\\)?](https://stackoverflow.com/questions/12091506/what-is-the-backslash-character) – Ole V.V. Jun 18 '20 at 06:38
  • String regex = "prefix\\.abcd\\.\\d+\\.pqr\\.\\d+\\.xyz|prefix\\.abcd\\.\\d+\\.xyz|prefix\\.pqr\\.\\d+\\.xyz"; works. I didnt realize I was quite close to the answer. Escaping \ and using \d+ helped. Can one of you post your comment as answer so that I can accept it? thanks – Zack Jun 18 '20 at 17:31

0 Answers0