问题
Given a string as the following, containing only 0 and 1 separated by spaces with an additional space at the end of each line.
I want to select only the spaces between the digits but not the one at the end of the line to search and replace them with ,.
When I try to create a RegEx I either select all spaces or the surrounding digits too.
GIVEN WANTED NOT WANTED TOTALLY NOT WANTED
0 1 0 1 0,1,0,1 0,1,0,1, ,,,,
0 0 1 0 0,0,1,0 0,0,1,0, ,,,,
1 0 1 0 1,0,1,0 1,0,1,0, ,,,,
1 1 0 0 1,1,0,0 1,1,0,0, ,,,,
1 1 1 0 1,1,1,0 1,1,1,0, ,,,,
1 1 0 0 1,1,0,0 1,1,0,0, ,,,,
So, how can I only select those spaces that have a digit on both sides, but not the digits. Is there some kind of syntax feature that matches but does not select?
Working answers:
As multiple answers were correct I want to collect them here. The accepted answer is the first one because it is the shortest regex and completely does what is needed.
(?!$) - please note there is a space at the beginning of this regex.
(?<=\d)\s(?=\d) or (?<=[01])\s(?=[01]) if your digits are either 0 or 1
回答1:
if you're sure that your text contains only 1 and 0 you can use this
regex (?!$) there is a space character at the beginning of regex
check this Demo
and if you're not sure you can use this one (?<=\d) (?=\d) but this is going to work only if look ahead and look behind is supported , I don't know which language you're using exactly , this is PERL regex
check the Demo
回答2:
You can use the following to match just the space between numbers and not the numbers:
(?<=\d)\s(?=\d) or (?<=[01])\s(?=[01]) if your digits are either 0 or 1
And replace with ,
See DEMO
回答3:
To select a group with digits on either side, you can use:
\d( )\d
Matched group 1 in this case will contain the space. Or you can replace the entire group by capturing both digits and just inserting your comma,
(\d) (\d)
Extracting groups 1 and 2 and putting a comma between them could work.
来源:https://stackoverflow.com/questions/30317726/regex-to-select-a-space-between-two-digits