tags:

views:

140

answers:

4

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.

A: 

Try this regular expression:

pervious90907(.*?)55544after

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

Gumbo
If I want to limited the result is digit only, what can I do?
Tattat
Replace the `.` with `[0-9]`, so `[0-9]*?`.
Gumbo
@Tattat: \dSee my answer for more info.
Renesis
Very fast response. thx u a lot.
Tattat
A: 

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
Renesis
very clear and fast respone.
Tattat
`\w` contains more word character than just `0`-`9`, `a`-`z`, `A`-`Z` and `_`.
Gumbo
@Gumbo, depends on the platform you are using
Renesis
A: 

The regex should be like this:

previous([0-9]*)after
Nick D
A: 
bash-3.2$ echo pervious909078375639355544after | perl -ne 'print "$1\n" if /pervious90907(.*)55544after/'
83756393
William Pursell