2013-08-17 192 views
-1

我想要一個不區分大小寫的表達式,它將在邏輯上找到: (stringA OR stringB)AND stringC。正則表達式查找

所以,如果stringA是「博士」 stringB是「醫生」和stringC是「推測」,我想這些結果:

Dr. Livinsgston I presume   TRUE 
Doctor Livingston I presume   TRUE 
Mr. Livingston I presume   FALSE 

不要緊,在測試字符串中的值存在,但如果我可以讓表達式要求(A或B)先於被測字符串中的C,那會更好。

這是可以用正則表達式嗎?

+3

在什麼味道.. javascript? java嗎? PHP的?例如 –

+1

stringC必須在stringA/stringB之後出現,還是可以按任意順序出現?我也會說正則表達式不是唯一的解決方法 - 用你相當簡單的標準,你可以通過幾個簡單的'in_string()'調用來獲得相同的結果(或者任何相關的函數,無論你使用什麼語言工作) – Spudley

+0

是或分裂,然後是一些含有 –

回答

0

非常適合正則表達式,但在這種情況下絕對沒有理由使用正則表達式。您沒有添加語言,所以這裏的Python中的簡單的解決方案:

def check_string(test_string): 
    lowered_string = test_string.lower() 
    doctor = lambda s: "dr" in s or "doctor" in s 
    presume = lambda s: "presume" in s 
    return doctor(lowered_string) and presume(lowered_string) 

一般要避免使用正則表達式只要有可能,你可以很容易地檢查不區分大小寫的只是在做你對證一個小寫字符串的版本(就像我上面所做的那樣)。

如果你想匹配它與正則表達式這裏是一個d'alar'cop的答案,實際工作的版本(移動到Python以保持我的答案內部一致):

import re 
return bool(re.match(r'(dr|doctor).*?presume',test_string.lower())) 
0

是的,你可以用re gexp。用grep你可以簡單地做到這一點

echo Doctor Livinsgston I presume | grep "^\(Dr\.\|Doctor\).*presume$" >/dev/null; [[ $? == 0 ]] && echo TRUE || echo FALSE 
TRUE 
echo Dr. Livinsgston I presume | grep "^\(Dr\.\|Doctor\).*presume$" >/dev/null; [[ $? == 0 ]] && echo TRUE || echo FALSE 
TRUE 
echo Mr. Livinsgston I presume | grep "^\(Dr\.\|Doctor\).*presume$" >/dev/null; [[ $? == 0 ]] && echo TRUE || echo FALSE 
FALSE 
1

上面發佈的Python解決方案做的工作;但在關閉的機會,你也只是想學習如何做這樣的事情,這裏有一個可能的解決方案(在JavaScript;語法可能在其他語言不同):

/(dr|doctor).*?presume/i.test(...); 

i在最後使它不區分大小寫(相當於預先將測試字符串轉換爲小寫字母)。括號內的單詞之間的|使得這兩個單詞可以互換。 .*?只是意味着在括號內的東西和presume之間可以有任何東西。

請注意,這意味着presume必須在括號內的東西之前。老實說,如果順序很重要,那麼正則表達式會帶來很多的痛苦。

1

在Perl中,你可以做這樣的事情..

(?:[Dd]r|Doctor).*(?:presume) 

正則表達式:

(?:      group, but do not capture: 
    [Dd]      any character of: 'D', 'd' 
    r      match 'r' 
    |      OR 
    Doctor    match 'Doctor' 
)       end of grouping 
.*      any character except \n (0 or more times) 
    (?:      group, but do not capture (1 or more times) 
    presume    match 'presume' 
)      end of grouping 

斷言的簡短說明。見Regex lookahead, lookbehind and atomic groups

(?=) Positive look ahead assertion 
(?!) Negative look ahead assertion 
(?<=) Positive look behind assertion 
(?<!) Negative look behind assertion 
(?>) Once-only subpatterns 
(?(x)) Conditional subpatterns 
(?#) Comment (?# Pattern does x y or z)