簡體   English   中英

僅當帶空格,句點或什么都沒有正則表達式時,才使用Python匹配字符串中的字母嗎?

[英]Use Python to match a letter in a string only when followed by a space, period, or nothing, without regex?

我正在嘗試編寫此代碼以提高可讀性,但是最后一個“ for x in measurement”顯然不起作用。

以下打印“ t”,但我不希望它與“ test”匹配
如果確實是測試用例,我確實希望它與“ this at at”的“ t”相匹配。

是否可以不使用正則表達式?

measurements = ['t', 'tsp', 'T', 'tbl', 'tbs', 'tbsp', 'c']
measurements = ([' ' + x + ' ' for x in measurements] + #space on either side
                [' ' + x + '.' for x in measurements] + #space in front, period in back
                [' ' + x + '' for x in measurements])   #space in front, nothing in back???

string_to_check = 'this is a test'

for measurement in measurements:
    if measurement in string_to_check:
        print(measurement)

在這里您可以使用re.search

>>> measurements = ['t', 'tsp', 'T', 'tbl', 'tbs', 'tbsp', 'c']
>>> measurements = ([' ' + x + ' ' for x in measurements] + [' ' + x + '\.' for x in measurements] + [' ' + x + r'\b' for x in measurements])
>>> measurements
[' t ', ' tsp ', ' T ', ' tbl ', ' tbs ', ' tbsp ', ' c ', ' t\\.', ' tsp\\.', ' T\\.', ' tbl\\.', ' tbs\\.', ' tbsp\\.', ' c\\.', ' t\\b', ' tsp\\b', ' T\\b', ' tbl\\b', ' tbs\\b', ' tbsp\\b', ' c\\b']
>>> string_to_check = 'this is a test'
>>> for measurement in measurements:
    if re.search(measurement, string_to_check):
         print(measurement)


>>>

我在這里做了兩件事。

  • [' ' + x + '\\.' for x in measurements] [' ' + x + '\\.' for x in measurements] ,請按順序轉義點以匹配文字點,因為點是regex中的特殊元字符,可以匹配任何字符。

  • [' ' + x + r'\\b' for x in measurements]添加字邊界\\b ,由於\\b單詞字符和非字符字之間的匹配,因此不會接spacet<space>test

問題在於,您所編碼的含義“與它無關”。

您已經在數組中包括了字符串't',它是字符串'this is a test'的子字符串[即,它位於單詞test的前面]。

如果您想讓“后面沒有內容”的意思是“字符串末尾”,那么您必須檢查字符串末尾是什么,而不是使用子字符串搜索。

測量
[' t ', ' tsp ', ' T ', ' tbl ', ' tbs ', ' tbsp ', ' c ', ' t.', ' tsp.', ' T.', ' tbl.', ' tbs.', ' tbsp.', ' c.', ' t', ' tsp', ' T', ' tbl', ' tbs', ' tbsp', ' c']

您可以在測量結果中找到“ t”。因此在您的檢查字符串“ this is aest”中找到“ t”。
因此,返回“ t”是正確的。

如果您想完全匹配't'而不是'txxx',則需要
[' ' + x + r'\\b' for x in measurements]

一種可能的非正則表達式方法是將string_to_check分成單詞列表。 然后in將尋找完全匹配的單詞。

measurements = ['t', 'tsp', 'T', 'tbl', 'tbs', 'tbsp', 'c']

string_to_check = 'this is a test'
words_to_check = string_to_check.replace('.', ' ').split()
for measurement in measurements:
    if measurement in words_to_check:
        print(measurement)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM