简体   繁体   English

如何在Python中匹配没有特定字符的字符串?

[英]How do I match a string without a specific character in Python?

Which regular expression pattern will match a substring not containing a specific character in Python? 哪个正则表达式模式将匹配包含Python中特定字符的子字符串? For example, I have the string "abc,5 * de" , and I want to match "abc" and "5 * de" as two substrings, but not the , . 例如,我有字符串"abc,5 * de" ,并且我想将"abc""5 * de"匹配为两个子字符串,但不能匹配,

Use a negated character class that contains all characters you don't want to match. 使用包含所有您不想匹配的字符的否定字符类

Something like 就像是

[^,]+

See it here on Regexr 在Regexr上查看

The [] denotes the character class and the ^ as first character makes it a negated class. []表示字符类, ^作为第一个字符使它成为否定类。

s = "abc,5 * de"
result = s.split(',')
result[0] # "abc"
result[1] # "5* de"

Regex expressions are not always the only way to solve string problems. 正则表达式并不总是解决字符串问题的唯一方法。

I don't know Python, but with all the regexp engines I know, that would be /[^,]*/ . 我不了解Python,但是使用我所知道的所有正则表达式引擎,它都是/[^,]*/ Or if Python has a built-in function to split a string on a regexp, then you could just split on /,/ . 或者,如果Python具有内置功能以在正则表达式上拆分字符串,则可以在/,/上拆分。

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

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