I am trying to write Regex to lookahead User name: and match the word behind until the end of line:

The regex is:

^(?=User name:)\s*\[A-Za-z]+

and the text is:

Action:         NEW

User name:      Matthew Thomas
Job title:      Dealer Account Manager
Direct report:      Craig Carlson
Department:         Dealer Account Management
Location:       Milton, QLD
Employment type:    Permanent Full Time
Start date:         15/07/2013
Finish date:

Decision Point 3
Read Only

closed as unclear what you're asking by Scott, fixer1234, n8te, G-Man, Pimp Juice IT Nov 20 '17 at 12:05

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    So what is your question? – music2myear Nov 16 '17 at 18:23

^(?=User name:)\s*\[A-Za-z]+

  • (?=User name:) what you need is lookbehind, not lookahead:
    (?<=User name:)
  • ^(?=User name:) - lookbehind will search at the beginning, regardless where you place it in your expression, so it's looking for "User name:" followed by beginning of line and some spaces. Include beginning of line too:
    (?<=^User name:)
  • put your name in brackets, so it'll be easier it capture it:
  • [A-Za-z] there can be also spaces in your name, or even some letters with accent, I would modify it like this:
    (a none space character (following white spaces) followed by everything until end of line)

The whole expression is: (?<=^User name:)\s*(\S.+)$

You can test is here.


It's not really clear what you want.

I put your sample text into text.txt file.

If you simply want to grep the line, there is the solution:

grep -E "^User name:\s*[A-Za-z ]+$" text.txt
User name:      Matthew Thomas

If you want only the name, we can enhance the command with sed:

grep -E "^User name:\s*[A-Za-z ]+$" text.txt | sed -e '1,$s/^User name:\s*\([A-Za-z ]*\)$/\1/'

Not the answer you're looking for? Browse other questions tagged or ask your own question.