开发者

Regex parsing multiple elements, with the first one being optional

开发者 https://www.devze.com 2022-12-13 19:46 出处:网络
I am trying to integrate my timesheets app with Fogbugz by using a text pattern in the time entry\'s notes to indicate that work was done on a case.

I am trying to integrate my timesheets app with Fogbugz by using a text pattern in the time entry's notes to indicate that work was done on a case.

Scenario A: If work was done on case#123, the note would be: [123] Rewrote javascript code.

Desired output: Case: 123 Note: Rewrote javascript code.

Scenario B: If work was not related to a case, the note would be: Rewro开发者_开发百科te javascript code.

Desired output: Case: Null Note: Rewrote javascript code.


To parse the string, I'm using Pentaho Data Integration's Regex Evaluation transformation, but I think the regex would probably be the same regardless of the tool in question.

This is the code that I'm using:

(\[(.*)\])(.*)

For Scenario A, I get: Ignorable field: [123] Case: 123 Note: Rewrote javascript code.

Scenario B, I get: Ignorable field: null Case: Null Note: Null

Now to the question (finally!) - is there a way for me to get the note portion to show up if there is no "[##]" pattern showing up?


You may want to try this:

(\[(.*)\])?\s*(.*)


^\s*(\[[^]]+\])?\s*(.*)

Don't use .* if you don't absolutely, positively want to match everything. What you are trying to match is "everything up to the closing ]", and this should be explicit in the regex.

Explanation:

^          # start-of-string
\s*        # any number of leading white-space (gets ignored)
(          # match group 1
  \[       # literal [
  [^]]+    # anything but ]
  \]       # literal ]
)?         # end match group 1, make optional
\s*        # any number of intermediary white-space (gets ignored, too)
(.*)       # anything else on that line


That's not strictly a regex problem. It consists of two parts: regex matching, and then apply a little logic: if the [n+] part matched, output "\1 Note" else "Null Note".

0

精彩评论

暂无评论...
验证码 换一张
取 消