0

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|"
2
  • 2
    Please, define the rule applied to extract the substring Commented Nov 26, 2014 at 10:37
  • Return substring that comes before any number with in the input string Commented Nov 27, 2014 at 4:52

2 Answers 2

1

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.
Sign up to request clarification or add additional context in comments.

Comments

0
$ 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.