Remove whitespace from within a regex capturing group

Viewed 2063

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

2 Answers

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")

Try this:

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

This should work.

Related