3

This should be a simple job, but this morning I just can't seem to find the answer I need

Value:

N.123456 7

Current regex

N.(\d{6}\s?\d)

Returns single matching group

123456 7

Want it to return single matching group

1234567

Thanks

Thomas Ayoub
  • 29,063
  • 15
  • 95
  • 142
mikelittlewood
  • 223
  • 4
  • 15
  • 4
    It is impossible to match discontinuous texts within one match operation. To remove matches, use a regex replace method/function. Or, capture into 2 groups (e.g. with `N.(\d{6})\s?(\d)`) and then join the values after a match is found. And a note: to match a literal `.` you should escape `.` in your pattern. – Wiktor Stribiżew Sep 06 '18 at 08:37
  • You could remove all whitespace before performing the regex – karen Sep 06 '18 at 08:38
  • 1
    So you mean you want `N\.(\d{6})\s?\d`? – revo Sep 06 '18 at 08:44
  • I don't have the opportunity to remove the whitespace before processing. I just need to return the 7 numbers only. I can easily do it in code later, but I would really like to be able to strip it out from the regex matching group itself if possible. – mikelittlewood Sep 06 '18 at 08:45
  • No revo, I need all 7 numbers – mikelittlewood Sep 06 '18 at 08:45
  • Considering seventh digit, you need to capture second part like in `N\.(\d{6})\s?(\d)` then work with back-references `\1\2`. – revo Sep 06 '18 at 08:49
  • @revo, he wants to concatenate the result, how will he do it? – The Scientific Method Sep 06 '18 at 08:54
  • @TheScientificMethod No way other than my last comment or with help of a replace functionality. – revo Sep 06 '18 at 09:02
  • 1
    Oh well, I guess I'll just have to do a string replace in code after getting the group matchers then. – mikelittlewood Sep 06 '18 at 09:26

2 Answers2

0

You can't return as single matching group. I think what are you looking for is non-capturing group (?: ).

There is explanation here

Maybe this regex would help you. It will exclude space character with non capturing group.

N.(\d{6})(?:\s?)(\d)

It will capture 123456 in group 1 and 7 in group 2.

What you want is probably this. It will return 1234567

"N.123456 7".replaceAll("N.(\\d{6})(?:\\s?)(\\d)", "$1$2")
exp2Tapavicki
  • 311
  • 3
  • 15
-2

Try this:

(?<=\d)\s+(?=\d+)

This should work.

Praneet Nadkar
  • 823
  • 7
  • 16