[英]Match a string with comma-separated sub strings, ensuring no leading/trailing commas, with regex in Kotlin
這類問題有很多變體,但我看不出完全符合我的需要 - 如果我錯過了不同的答案,我深表歉意。
作為單元測試的一部分,我想測試給定的字符串是否匹配正則表達式模式。 該字符串通常采用以逗號分隔的形式,使用相同順序的同一組子字符串:
客戶、潛在客戶、聯系人、機會
但是,有時某些子字符串可能不存在。 例如,字符串可能是:
賬戶、聯系人
或者:
潛在客戶、機會
該字符串也可以為空。
我想要的是一個正則表達式模式,它總是匹配這個字符串的變體,並確認它周圍沒有尾隨或前導逗號。 到目前為止我有:
"^[^,]?(accounts,?)?(leads,?)?(contacts,?)?(opportunities)?[^,]?$".toRegex()
但這不起作用,因為正則表達式仍將接受一個尾隨空格或逗號,或周圍除逗號以外的字母。 我不擅長正則表達式,因此不勝感激。
需要匹配的示例:
accounts,leads,contacts,opportunities // match
<emptystring> // match
accounts,opportunities // match, substrings are in correct order
leads,opportunities // match, substrings are in correct order
leads,accounts,contacts // no match, wrong order of substrings
accounts,leads,contacts, // no match, trailing comma
,accounts,leads,contacts // no match, leading comma
apples,bananas,contacts // no match, invalid substrings
你需要使用
^(?:accounts)?(?:(?:,|^)leads)?(?:(?:,|^)contacts)?(?:(?:,|^)opportunities)?$
請參閱正則表達式演示。 這基本上是一個按指定順序排列的可選組鏈:
^
- 字符串的開始(?:accounts)?
- 可選accounts
字符串(?:(?:,|^)leads)?
- 一個可選的,
或字符串的開頭然后leads
字符串(?:(?:,|^)contacts)?
- 可選的,
或字符串的開頭,然后是contacts
字符串(?:(?:,|^)opportunities)?
- 一個可選的,
或字符串的開頭,然后是opportunities
字符串$
- 字符串結尾。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.