Home > Software engineering >  How to make Ruby regex expression with some conditional inputs
How to make Ruby regex expression with some conditional inputs

Time:09-28

This is my inputs looks like

format 1: 2022-09-23 18:40:45.846 I/getUsers: fetching data

format 2: 11:54:54.619 INFO loadingUsers:23 - visualising: "Entered to dashboard

This is the expression which is working for format one, i want to have the same (making changes to this) to handle both formats

^([0-9-]  [:0-9.] )\s(?<level>\w )[\/ ](?<log>.*)

it results as for format 1:

level I

message getUsers: fetching data

for 2nd it should be as

level INFO

message loadingUsers:23 - visualising: "Entered to dashboard

Help would be appreciated, Thanks

CodePudding user response:

You can use

^([0-9-]  [:0-9.] |[0-9:.] )\s(?<level>\w )[\/ \s] (?<log>.*)

See the Rubular demo.

Details:

  • ^ - start of a line
  • ([0-9-] [:0-9.] |[0-9:.] ) - Group 1: one or more digits/hyphens, space, one or more digits/colons/dots, or one or more digits/colons/dots
  • \s - a whitespace
  • (?<level>\w ) - Group "level": one or more letters, digits or underscores
  • [\/ \s] - one or more slashes, or whitespaces
  • (?<log>.*) - Group "log": zero or more chars other than line break chars as many as possible.

If you want to precise your Group 1 pattern (although I consider using a loose pattern fine in these scenarios), you can replace ([0-9-] [:0-9.] |[0-9:.] ) with (\d{4}-\d{1,2}-\d{1,2} \d{1,2}:\d{1,2}:\d{1,2}\.\d |\d{1,2}:\d{1,2}:\d{1,2}\.\d ), see this regex demo.

  • Related