Regex Skip space in match

≡放荡痞女 提交于 2021-02-05 08:00:45

问题


I have a string of digits that represent 3 different lenghts. I need to pick out the second length in the string but can't find away to exclude the white space from the match. Here is an example for the string. It has always 6 digits after the dot but before it vary. In this case it is 907.086614 that I need to match exactly.

1417.322835 907.086614 2.267717

^\s(\d+\.\d{6})

I've played around with different look behind but can't get it to exclude the white space.


回答1:


You can try this

(?<=\s)(\d+\.\d{6})(?=\s)

see demo

But if you still want to use your pattern, remove the begin of line anchor ^ and match group 1

i.e \s(\d+\.\d{6})

see demo




回答2:


A potential side effect of \s is that it matches carriage returns.

Example mistaken match

Since you are looking for the second column of a group of floats, it is better to be explicit:

\d[ \t](\d+\.\d+)[ \t]\d

^                          trailing digit from first col
   ^                       a single space or tab
         ^  ^ ^            capture float
                   ^       single space or tab
                       ^   leading digit of third col

Demo

You can also place the capture between a look ahead and lookbehind:

(?<=\d[ \t])(\d+\.\d+)(?=[ \t]\d)

Demo




回答3:


How about with a positive look behind like:

(?<=\s)(\d+\.\d{6})

Online Demo

(?<=\s) Positive Lookbehind - Assert that the regex below can be matches the \s



来源:https://stackoverflow.com/questions/33199886/regex-skip-space-in-match

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!