Match a part of a string using regex

I have a string and would like to match a part of it.

The string is Accept: multipart/mixedPrivacy: nonePAI: <sip:[email protected]>From: <sip:[email protected]>;tag=5430960946837208_c1b08.2.3.1602135087396.0_1237422_3895152To: <sip:[email protected]>

I want to match PAI: <sip:4168755400@ the whitespace can be a word so i would like to use .* but if i used that it matches most of the string

The example on that link is showing what i'm matching if i use the whitespace instead of .*

(PAI: <sip:)((?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4})@

The example on that link is showing what i'm trying to achieve with .* but it should only match PAI: <sip:4168755400@

(PAI:.*<sip:)((?:\([2-9]\d{2}\)\ ?|[2-9]\d{2}(?:\-?|\ ?))[2-9]\d{2}[- ]?\d{4})@

I tried lookaround but failing. Any idea? thanks

Upvotes: 0

Views: 76

Answers (2)

Wathanyu Phromma
Wathanyu Phromma

Reputation: 33

The regex should be like

PAI:.*?(<sip:.*?@)

Explanation:

  • PAI:.*? find the word PAI: and after the word it can be anything (.*) but ? is used to indicate that it should match as few as possible before it found the next expression.
  • (<sip:.*?@) capturing group that we want the result.
  • <sip:.*?@ find <sip: and after the word it can be anything .*? before it found @.

Example

Upvotes: 2

The fourth bird
The fourth bird

Reputation: 163577

Matching the single space can be updated by using a character class matching either a space or a word character and repeat that 1 or more times to match at least a single occurrence.

Note that you don't have to escape the spaces, and in both occasions you can use an optional character class matching either a space or hyphen [ -]?

If you want the match only, you can omit the 2 capturing groups if you want to.

(PAI:[ \w]+<sip:)((?:\([2-9]\d{2}\) ?|[2-9]\d{2}[ -]?)[2-9]\d{2}[- ]?\d{4})@

Regex demo

Upvotes: 2

Related Questions