Home > OS >  REGEX How do I match all of the middle of a sentence?
REGEX How do I match all of the middle of a sentence?

Time:11-20

I need to regex replace everything in a long string with the first word, new word, last word. I can match the first and last no problem but I am having all kinds of issues trying to match the middle. Sample data:

tunnel4 connection to router 1 status
gig1/0/1 blah status
g2/0/1 foo bandwidth

Output:

tunnel4 router1 status
gig1/0/1 router1 status
g2/0/1 router1 bandwidth

Match first word works:

^([^\s] )

Match last word works:

([^\W] $)

The replace would be $1 router1 $2 but I can't figure out how to match the middle. I was trying to match 1st space to last space and I could not seem to get that to work.

CodePudding user response:

You can try

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

View demo here

  • Related