Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing everything except numbers inside braces and some characters

Tags:

regex

php

Want to remove everything except # NewLine, complete bracket set and numbers inside braces.
Sample input:

# (1296) {20} [529] [1496] [411]
# (MONDAY ) (1296)
# (646) {20} (BEACH 7) [20 Mtrs] { 03 Foot }
# {19} [455] [721] (1296) (SUNDAY ) [2741] (MONDAY (WEDNESDAY {20}
# {19} (1296)

Code which does not work:

$re = '/(?:\[[^][]*]|\([^()]*\)|{[^{}]*})(*SKIP)(*F)|[^][(){}@#]+/m';
$result = preg_replace($re, '', $input);

Incorrect output:

#(1296){20}[529][1496][411]
#(1296) 
#(646){20}(BEACH 7)[20 Mtrs]{ 03 Foot }
#{19}[455][721](1296)[2741](({20}
#{19}(1296)

Desired output:

#(1296) {20} [529] [1496] [411]
#(1296)
#(646) {20}
#{19} [455] [721] (1296) [2741] {20}
#{19} (1296)
like image 363
www.friend0.in Avatar asked Jan 19 '26 18:01

www.friend0.in


1 Answers

You could match at least 1 digit between the brackets and then skip that match.

Then match any char except a newline or # to be replaced with an empty string.

(?:\[\h*\d[\h\d]*]|\(\h*\d[\h\d]*\)|{\h*\d[\h\d]*})\h*(*SKIP)(*F)|[^#\n]

Explanation

  • (?: Non capture group
    • \[\h*\d[\h\d]*] Match at least 1 digit between square brackets, where \h matches horizontal whitespace characters (no newlines)
    • | Or
    • \(\h*\d[\h\d]*\) 1 digit between parenthesis
    • | Or
    • {\h*\d[\h\d]*} 1 digit between curly braces
  • )\h* Close the non capture group and match 1+ spaces
  • (*SKIP)(*F) Skip and fail the match (to leave it untouched in the output)
  • | Or
  • [^#\n] Match any character except # or a newline

Regex demo

like image 81
The fourth bird Avatar answered Jan 21 '26 06:01

The fourth bird



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!