PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 6, 2022

[FIXED] How to get text that is before and after of a matched group in a regex expression

 November 06, 2022     regex, regex-group     No comments   

Issue

I have following regex that matches any number in the string and returns it in the group.

^.*[^0-9]([0-9]+).*$  $1

Is there a way I can get the text before and after of the matched group i.e. also as my endgoal is to reconstruct the string by replacing the value of only the matched group.

For e.g. in case of this string /this_text_appears_before/73914774/this_text_appears_after, i want to do something like $before_text[replaced_text]$after_text to generate a final result of /this_text_appears_before/[replaced_text]/this_text_appears_after


Solution

You only need a single capture group, which should capture the first part instead of the digits:

^(.*?[^0-9])[0-9]+

Regex demo

In the replacement use group 1 followed by your replacement text \1[replaced_text]

Example

pattern = r"^(.*?[^0-9])[0-9]+"
s = "/this_text_appears_before/73914774/this_text_appears_after"
 
result = re.sub(pattern, r"\1[replaced_text]", s)
if result:
    print (result)

Output

/this_text_appears_before/[replaced_text]/this_text_appears_after

Other options for the example data can be matching the /

^(.*?/)[0-9]+

Or if you want to match the first 2 occurrences of the /

^(/[^/]+/)[0-9]+


Answered By - The fourth bird
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing