Search code examples
regexsearchjava-8lookbehind

Lookbehind behavior


Why doesn't the following lookbehind

(?<=to my\s)(checking|savings|CD) | (?<=to\s)(checking|savings|CD)

return any matches on:

Can you transfer from my CD 200 dollars to my checking, please?

despite properly returning a match (checking) on:

Can you transfer from my CD 200 dollars to checking, please?

The following however works in both cases:

(?<=from my\s)(checking|savings|CD) | (?<=from\s)(checking|savings|CD)

Can you transfer from my CD 200 dollars to checking, please? --> CD

Can you transfer from CD 200 dollars to checking, please?  --> CD

I am trying to formulate a regular expression which is able to parse out the destination [which follows 'to'] on the above plus on the following text strings (or similar) as well:

- Transfer $20 from checking to savings please.
- Can you transfer from my CD 200 dollars to my checking, please?
- Please send from savings to checking 45.

Solution

  • Maybe you could do it without a lookbehind and make "my " optional (?:my )?:

    to (?:my )?(checking|savings|CD)

    "checking" or "savings" or "CD" will be in captured group 1.