Match between two strings + concatenation

I have this text:

2015-10-01 15:15:30 subject: Announcement: [Word To Find] Some other thext

      

My goal is to align date with time:

(?s)(?<=^)(.+?)(?= subject\: Announcement\: )

      

And also the text inside [ ]

(?s)(?<=\[)(.+?)(?=\])

      

How do I get these two results in one regex?

+3


source to share


4 answers


Use the regular expression alternation operator.

^(?s).*?(?= subject\: Announcement\: )|(?<=\[)[^\]]*(?=\])

      



DEMO

+1


source


I'm going to call back with a working regex, which, while similar to the other answers, removes all redundancies:

^(?s)(.*?) subject: Announcement: \[(.*?)]

      

What the groups give:

1. "2015-10-01 15:15:30"
2. "Word To Find"

      



Watch live demo .

Dismissal:

  • No need to leave ]

    except character class
  • Colon should never be avoided :

  • Appearance (?<=^)

    is just identical ^

    as both are zero width assertions
+3


source


A simple regular expression can be used for this:

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

      

or

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

      

The first group contains the date, the second contains the text inside [].

+1


source


You can use the following regex to get both matches:

(?<=^|\[)(.*?)(?=subject|\])

      

see demo https://regex101.com/r/hU2iZ3/2

Note that all you need is to use logical OR ( |

) between your previous tokens and the following tokens.

Also note that if you have other parentheses in the text, you must use a negative character class instead .*

:

(?<=^|\[)([^[\]]*?)(?=subject|\])

      

+1


source







All Articles