我想用Python正则表达式检查单词。你知道吗
我的单词定义为字母数字[a-zA-Z0-9],并由非字母数字[^a-zA-Z0-9]分隔。你知道吗
而且单词应该被内部字符删减,用*代替,其他的保持不变。你知道吗
例如:
test=y
tes't
test'
test-y
tes-ty
test Test
test
abcdefg Test ... test are the best... some thing words @@$: HAHA TEST ONE REAL PLAYER!!! EXCELLENT! It's testy night
应该是结果
t**t=y
tes't
t**t'
t**t-y
tes-ty
t**t T**t
t**t
abcdefg T**t ... test are the best... some thing words @@$: HAHA T**T ONE REAL PLAYER!!! EXCELLENT! It's testy night
我试着用正则表达式来做这件事。 我在python3中使用re模块。你知道吗
1.我试着匹配模式。你知道吗
2.以匹配的模式捕获组,而不使用删失词。你知道吗
3.试着用这个词把小组连在一起。你知道吗
例如: 我试图审查“测试”这个词。你知道吗
因为我不知道如何用*替换它,所以我首先尝试用'SUB'替换以查看我的模式是否正确。你知道吗
inputStr = re.sub(r'([^a-zA-z0-9]+)test([^a-zA-z0-9]+)', r'\1SUB\2', inputStr, flags=re.IGNORECASE)
inputStr = re.sub(r'^test([^a-zA-z0-9]+)', r'SUB\1', inputStr, flags=re.IGNORECASE)
replacedStr = re.sub(r'([^a-zA-z0-9]+)test$', r'\1SUB', inputStr, flags=re.IGNORECASE)
print(replacedStr)
另外,有没有可能用一行来做以上的事情,我不知道如何使用一行模式的组。你知道吗
replacedStr = re.sub('[^a-zA-z0-9]+test[^a-zA-z0-9]+|^test[^a-zA-z0-9]+|[^a-zA-z0-9]+test$', 'SUB', inputStr, flags=re.IGNORECASE)
但效果不好。你知道吗
re.sub('[^a-zA-z0-9]+test[^a-zA-z0-9]+|^test[^a-zA-z0-9]+|[^a-zA-z0-9]+test$', 'SUB', inputStr, flags=re.IGNORECASE)
我的结果
SUB=y
tes't
SUB'
test-y
tes-ty
SUB Test
SUB
abcdefg SUB ... test are the best... some thing words @@$: HAHA SUB ONE REAL PLAYER!!! EXCELLENT! It's testy night
我看到我的模式有些不符合一些'测试',我不知道为什么。 https://regexr.com/3nk9l
所以,我的问题是
1.我的模式怎么了?你知道吗
2.如何让匹配的单词在其内部被*替换?你知道吗
泰铢
我认为与其显式匹配
^test
、^test$
和test$
(我认为您的正则表达式正在下降),不如使用look ahead and behind assertions来分隔单词,然后替换内部字母。你知道吗结果:
你可以试试这个:
替换为:
Python demo:
相关问题 更多 >
编程相关推荐