简体   繁体   English

检查多个正则表达式模式

[英]Check multiple regex patterns

I am working on a calculator for feet and inch calculations. 我正在开发用于英尺和英寸计算的计算器。 I currently have a program that works but so far I can only get it to work if you input the full measurement (ie 4'-0" instead of just 4' or 0'-6" instead of just 6"). I would like to be able to have it check against a few patterns as to be able to input just feet, inches, fractions of an inch, or a combination of the above. 我目前有一个可以运行的程序,但到目前为止,只有输入完整的尺寸(即4'-0“而不是4'或0'-6”而不是6“),我才能使它正常工作。我会希望能够对照几种模式进行检查,以便仅输入英尺,英寸,英寸的分数或以上各项的组合。

I have tried making one variable with all the different patterns in it but I must be missing something to be able to parse through the variable to find the correct pattern (this attempted is commented out in the code). 我试图用一个变量使用所有不同的模式,但是我必须缺少一些东西才能解析该变量以找到正确的模式(此尝试在代码中已注释掉)。 I found other code using this method and tried to replicate it to work for me but no luck. 我发现其他使用此方法的代码,并尝试将其复制为我工作,但是没有运气。 I have also tried making each pattern its own variable but then I was unsure how to check against each pattern and return whether or not it was a match. 我也尝试过将每个模式设置为自己的变量,但是我不确定如何对照每个模式并返回是否匹配。 Maybe I am over thinking this and its easy but I am stumped. 也许我在考虑这个问题并且很容易,但是我很沮丧。

Sorry for posting a link to the entire code but I figured that it was easier for you to be able to see and use what I am working with instead of just code snippets. 很抱歉,发布了指向整个代码的链接,但我认为您可以更轻松地查看和使用我正在使用的内容,而不仅仅是代码段。 Thanks in advance for any help. 在此先感谢您的帮助。

Link to the code: 链接到代码:

https://repl.it/repls/PrestigiousKeyMemorypool https://repl.it/repls/PrestigiousKeyMemorypool

Try using named groups and make each part optional (including the dash): 尝试使用命名组并将每个部分设为可选(包括破折号):

regex = re.compile(r'(?P<feet>[0-9]+\')?\-?(?P<inches>[0-9]+")?')

And modify the following functions and you will be set. 并修改以下功能,您将被设置。

def ftbreakdown(*args):
  search = regex.search(*args)
  print(search)
  feetsearch = search.group('feet')
  feet = int(feetsearch.split("'")[0]) if feetsearch is not None else 0
  return feet

def inbreakdown(*args):
  search = regex.search(*args)
  print(search)
  if search is None:
    inches = 0
  else:
    inchsearch = search.group('inches')
    inches = int(inchsearch.split('"')[0]) if inchsearch is not None else 0
  # print(inches)
  return inches

This is the quick and dirty way, but it works. 这是一种快速而肮脏的方法,但是它可以工作。 You can obviously poptimize this further. 您显然可以进一步对此进行优化。

Sample run 样品运行

Python 3.6.1 (default, Dec 2015, 13:05:11)
[GCC 4.8.2] on linux
Enter length: 4'-2"
Choose operation: +
Enter length: 6"
<_sre.SRE_Match object; span=(0, 5), match='4\'-2"'>
<_sre.SRE_Match object; span=(0, 2), match='6"'>
<_sre.SRE_Match object; span=(0, 5), match='4\'-2"'>
<_sre.SRE_Match object; span=(0, 2), match='6"'>
4'-8"
Choose operation:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM