简体   繁体   中英

Using Regex To Parse Multiline Console Output

I am building a service that calls a program I have already written to do some work. I am using a process to call an exe & pass it some arguments. I am listening to the output of the program so I can determine the success of the process for use in my program.

I am having problems writing the regex to parse the following logs. Below is an example of some of the cmd outputs, as you can see some of the outputs can be multi line.

[My Custom Exe][2018-05-24 11:03:01] Starting Process
[My Custom Exe][2018-05-24 11:03:01] Getting config
[My Custom Exe][2018-05-24 11:03:02] Beginning operation
[My Custom Exe][2018-05-24 11:03:02] Could not complete this operation, invalid inputs
[My Custom Exe][2018-05-24 11:03:02] Available inputs are:

- 1: Mode 1
- 2: Mode 2
- 3: Mode 3
- 4: Mode 4
- 5: Mode 5

[My Custom Exe][2018-05-24 11:03:02] Exiting Program

When I get this output from the program, I need to parse a string so I am using regex to create an array of console outputs.

I want to parse the console outputs by every new log, so everything I see [My Custom Exe] I want to add a new index to the array containing everything after this string, until it see's [My Custom Exe] again, where it will start over.

For this example I should have 6 elements in my array, I have managed to get my Regex working for single lines, however I cannot get all of entry 5 into my statement.

My Regex String = /\\[(.*?)\\](.*)/g

Here is a link to a demo of this regex, so you can see my issue.

I'm very new to RegEx and couldn't find much useful information on doing this type of parse.

Thanks

You could try:

(?m)^\[([^]]*)\](.*\n?(?!^\[))*

The flow goes in this manner:

Match a line that begins with brackets [...] then match up to end of line using greedy dot .* . Now at the end of line match a newline character \\n (optional) and see if next line doesn't start with brackets again. if it doesn't (done by negative lookahead (?!^\\[) ), repeat the same group of regex ( * means as many as possible or nothing).

See live demo here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM