Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract percentage text using regex?

Tags:

regex

From a text file I have to find all the line which have containing percentages (numbers + % or percent) for this I have created a regex but it doesnot work correctly.

regex string: \b(\d+(%|(percent)))\b

and my inputs are

  • 423%
  • 423%:
  • 10percent
  • 10percent:

for 1st two cases it is not matching but for 3rd and 4th it works.

My requirement is to identfy the line which having numbers + % or percent and around it there should be no alphabate or number

like image 846
madan Avatar asked Nov 15 '25 08:11

madan


1 Answers

The word boundary after % prevents it from matching before non-word chars.

Use

\b\d+(?:%|percent\b)

See the regex demo

The pattern matches:

  • \b - a leading word boundary
  • \d+ - 1+ digits
  • (?:%|percent\b) - one of the two alternatives:
    • % - a percentage sign
    • percent\b - word percent followed with a word boundary.
like image 81
Wiktor Stribiżew Avatar answered Nov 18 '25 12:11

Wiktor Stribiżew



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!