Home > Mobile >  Extract digits within different scopes in String using regex
Extract digits within different scopes in String using regex

Time:09-10

I want to extract all digits within different scopes.

1st scope: $ $
2nd scope: # #

Extract all digits within the 1st scope

$1-2$

Wished result

1, 2 

$1#4#-2$

Wished result

1, 2

Extract all digits within the 2nd scope

$1-2#4-9-6#3-4$

Wished result

4, 9, 6

Note The - is there to separate each digit and the number of digits in each scope may differ from time to time

My current Regex: (^[$])([\d] )(|-\d )*(|#[\d] ((|-\d )*)#)([$] )($)

Any help is appreciated!

CodePudding user response:

For scope-1 matches you can use this regex:

(?:\$|(?!^)\G(?:#[^#]*#)?-)\K\d (?=[-\d#]*\$)

# without \K for Java
(?:\$|(?!^)\G(?:#[^#]*#)?-)(\d )(?=[-\d#]*\$)

RegEx Demo 1

For scope-2 matches you can use this regex:

(?:#|(?!^)\G(?:\$[^$]*\$)?-)\K\d (?=[\d$-]*#)

# without \K for Java
(?:#|(?!^)\G(?:\$[^$]*\$)?-)(\d )(?=[-\d$]*#)

RegEx Demo 2

RegEx Breakup:

  • \G asserts position at the end of the previous match or the start of the string for the first match. Thus (?!^)\G matches position at the end of previous match
  • \K: Reset matched info
  • (?=[\d$-]*# is lookahead to assert that we have presence of # after matching 0 or more digits/$/-
  • (?=[\d#-]*\$ is lookahead to assert that we have presence of $ after matching 0 or more digits/#/-
  • Related