RegExp: Matching and substituting a part of it 
Author Message
 RegExp: Matching and substituting a part of it

Hi!

I am searching for a way to substitute a part of a matched string. For
instance, I would like to parse a file for occurences of [0-9]u and replace
the u with a x. However the number should stay the same.

As an example, a line ...
u5 4u u
should become ...
u5 4x u

I don't know of a way to keep the matched number in an regular expression.
Something like s/[0-9]u/[0-9]x/g with [0-9] the matched number would be
great, but it does not work.

Thank you for your help,
Mathias



Mon, 08 Nov 2004 22:55:51 GMT  
 RegExp: Matching and substituting a part of it

Quote:

> I am searching for a way to substitute a part of a matched string. For
> instance, I would like to parse a file for occurences of [0-9]u and replace
> the u with a x. However the number should stay the same.

> As an example, a line ...
> u5 4u u
> should become ...
> u5 4x u

> I don't know of a way to keep the matched number in an regular expression.
> Something like s/[0-9]u/[0-9]x/g with [0-9] the matched number would be
> great, but it does not work.

s/(\d)u/${1}x/g

John
--
use Perl;
program
fulfillment



Mon, 08 Nov 2004 23:32:21 GMT  
 RegExp: Matching and substituting a part of it

Quote:

> I am searching for a way to substitute a part of a matched string.
> For instance, I would like to parse a file for occurences of [0-9]u
> and replace the u with a x. However the number should stay the same.

You could capture the digit with parens and include the captured
value in the substitution:

  s/(\d)u/${1}x/g;
  # ^  ^ matches a digit and a 'u', puts the digit in $1

Or you could use a look-behind and leave the digit out of the match:

  s/(?<=\d)u/x/g;
  # ^^^^  ^ matches 'u' if it follows a digit

Quote:
> I don't know of a way to keep the matched number in an regular
> expression.

There's lots of information out there.

  $ perldoc perlrequick
  $ perldoc perlre

--
Steve

perldoc -qa.j | perl -lpe '($_)=m("(.*)")'



Mon, 08 Nov 2004 23:29:09 GMT  
 
 [ 3 post ] 

 Relevant Pages 

1. substitute part of the match

2. regexp matching with optional part

3. Pattern Match - substitute a string after the match

4. split and substitute, substitute, substitute

5. Newbie Q: variable replacement part of substitute

6. RegExp /g shall substitute more often

7. RegExp /g shall substitute more often

8. regexp - substitute everything than

9. substituting "@" with regexp

10. regexp substituting with processing

11. Substituting a return value into a regexp

12. substituting for matches not inside quotes?

 

 
Powered by phpBB® Forum Software