Tattat
Tattat

Reputation: 15778

How to extract value betwen two string using regex?

Here is the demo String:

beforeValueAfter

Assume that I know the value I want is between "before" and "After" I want to extact the "Value" using the regex....

pervious909078375639355544after

Assume that I know the value I want is between "pervious90907" and "55544after" I want to extact the "83756393" using the regex....

thx in advance.

Upvotes: 1

Views: 23463

Answers (4)

William Pursell
William Pursell

Reputation: 212218

bash-3.2$ echo pervious909078375639355544after | perl -ne 'print "$1\n" if /pervious90907(.*)55544after/'
83756393

Upvotes: 0

Nick Dandoulakis
Nick Dandoulakis

Reputation: 43110

The regex should be like this:

previous([0-9]*)after

Upvotes: 0

Nicole
Nicole

Reputation: 33197

The answer depends on two things:

  • If you know exactly what the value consists of (if you know it will be digits, etc., it makes it easier). If it could be anything, the answer is a little harder.
  • If your system is greedy/ungreedy by default, it affects the way you'd set up the expression. I will assume it is greedy by default.

If it can be anything (the ? will be needed to toggle the .* to ungreedy because ".*" also matches "After":

/before(.*?)After/

If you know it is digits:

/before(\d*)After

If it could be any word characters (0-9, a-z, A-Z, _):

/before(\w*?)After

Upvotes: 6

Gumbo
Gumbo

Reputation: 655189

Try this regular expression:

pervious90907(.*?)55544after

That will get you the shortest string (note the non-greedy *? quantifier) between pervious90907 and 55544after.

Upvotes: 0

Related Questions