Murali Mopuru
Murali Mopuru

Reputation: 6570

Extract substring using perl regex

How to extract substring using perl regex for following?

Input: firstString123456lastString
Output: firstString

Input: first$String 123456 last@String
Output: first$String

Something similar to

echo "firstString123456lastString" | sed -e "s|\([a-z]*\)[0-9].*|\1|"

Upvotes: 0

Views: 368

Answers (2)

Joe
Joe

Reputation: 26

$ echo "firstString123456lastString" | perl -pe 's/^([a-zA-Z]*)\d.*/$1/'
firstString

$ echo 'first$String 123456 last@String' | perl -pe 's/^([^\d\s]*).*/$1/'
first$String

Upvotes: 0

Avinash Raj
Avinash Raj

Reputation: 174696

Through sed,

$ echo 'firstString123456lastString' | sed 's/^\([^0-9 ]*\).*/\1/'
firstString
$ echo 'first$String 123456 last@String' | sed 's/^\([^0-9 ]*\).*/\1/'
first$String

Explanation:

  • ^ Asserts that we are at the start.
  • [^0-9 ]* Negated character class which matches any character but not of numbers or space zero or more times.
  • ([^0-9 ]*) Matched characters are captured by the group index 1.

Upvotes: 1

Related Questions