Capture digit between parentheses

Asked

Viewed 530 times

1

I have several types of texts, such as: $ticker="08.070.838/0001-63.offset(1)".

I want to capture the text and the digit, if any, which is in parentheses to turn it into the form "08.070.838/0001-63.offset+1".

I’m trying for the regex '(\S*)\((\d)\)' used in php by preg_match as follows:

if(preg_match('(\S*)\((\d)\)', $ticker, $match)) $ticker=$match[0]."+".$match[1];;

But it is returning the error message:

Warning: preg_match(): Unknown Modifier '\'.

Would anyone know what’s wrong with any of these \?

  • 1

    What language are you using?

  • 3

    I’m trying to use regular expressions by PHP

  • Matcher textoParenteses = Pattern.compile("(.)").matcher(textoOrignal) String textNovo = textoParenteses.replace('(','+').replace(')','') This in Java in the case, I believe that to adapt to PHP

  • Try $res = preg_replace('\((?=\w*\d*\))', '', $ticker); demo and $res = preg_replace('\)(?=$)', '+', $ticker); demo to replace the parents.

1 answer

1


I want to capture the text and digit (if any) that is in parentheses

Try this regex: (".*?)\((\d*?)\)

[...] to transform it into the form "08.070.838/0001-63.offset+1".

To make this transformation you must use the method preg_replace thus:

<?php
$string = '08.070.838/0001-63.offset(1)';
$pattern = '/(".*?)\((\d*?)\)/g';
$replacement = '$1+$2';
echo preg_replace($pattern, $replacement, $string);
?>

You can see how this regex works here.

Explanation:

Capture pattern:
- (.*?)\( - Captures all text up to the (.
- (\d*?)\) - Captures all digits after the ( up to the ).

Replacement:
- $1+ - Plays what is captured in group 1 with a + symbol after content.
- $2 - Reproduce what is captured in group 2.

Would anyone know what’s wrong with any of these \?

You are not using delimiters in your expression, you’re putting it raw, you should always start with the delimiter "/" to start the pattern and if you want to end with the modifier desiring.

You can find documentation on delimiters here

Browser other questions tagged

You are not signed in. Login or sign up in order to post.