RegEx find string containing numbers with one space, two spaces or no space at all followed by / and four numbers

試著忘記壹切 提交于 2020-03-05 00:26:29

问题


I need to use RegEx to find a string in Word document. The string contains numbers{1;5} with one space, two spaces or no space at all followed by / and four numbers{4} which denotes a year in which the document was created.

The strings I need to find are like these:

  • 45 /2017
  • 125 /2019
  • 1245 /2018
  • 12577 /2019
  • 37589 /2017

but sometimes there is no space in between:

  • 45/2017
  • 125/2019
  • 1245/2018
  • 12577/2019
  • 37589/2017

and sometimes there is two spaces:

  • 45 /2017
  • 125 /2019
  • 1245 /2018
  • 12577 /2019
  • 37589 /2017

but it's always in the same place - the space or two spaces. It's always after the first string of numbers, which are never more than 5 digits - therefore I type [0-9]{1;5} in RegEx.

But when I tried to build this RegEx expression in Word's Ctrl+H find and replace dialog box, and I test it against the Word's document I cannot build universal expression to find these strings with space and no space. The ? is not working for me. I've read here that ? should find one space or no space, but when I'm testing it in my Word document it finds a string with two spaces inside, but not the one with one space or no space at all.

Here are the RegExs I've tried, which failed to match both strings with no space inside like 4125/2019, as well as similar strings with one or two spaces:

  1. [0-9]{1;5} ?/[0-9]{4}

  2. [0-9]{1;5}\s?/[0-9]{4}

  3. [0-9]{1;5}[ ]{0;2}/[0-9]{4} this gives an error but [0-9]{1;5}[ ]{1;2}/[0-9]{4} finds 125 /2019 but doesn't find 125/2019 and 12577/2019.

In Polish version of MS Word/Excel we use ; instead of , in formulas, but I tried it all with colon or semi-colon interchangeably.

I've read these sources: How to use Regular Expressions (Regex) in Microsoft Excel both in-cell and loops

and

Regex- Space or no space

Analyst_Cave

Regular Expression Tester


回答1:


You can use a Word wildcard Find expression like:

<[0-9 ]{1;7}/[0-9]{4}>

without the need to involve the RegEx library.




回答2:


Try

([0-9]{1,5})([ ]{0,4})([/])([0-9]{4})

or

([0-9]{1,5})([\s]{0,4})(/[0-9]{4})

According to the test, all three are good.



来源:https://stackoverflow.com/questions/60233258/regex-find-string-containing-numbers-with-one-space-two-spaces-or-no-space-at-a

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