Having Regex Troubles



确实需要一些Regex帮助。

我正在尝试创建bash IF语句,如果它遇到三个单独的文本条件中的任何一个,就会抛出特定的错误消息。

第一种是当一系列6个字母数字后面只有逗号时

WA16B7, 
1AAA42, 
5A5CC5,

第一种情况是,一系列6个字母数字后面要么没有,要么有空格。

WA16B7
1AAA42
5A5CC5

第三种情况是,一系列6个字母数字后面跟着一个空格,或一系列空格,然后是其他随机文本。

WA16B7 Test1
1AAA42  Test2
5A5CC5   Test3

另一方面,我需要以下值才能顺利通过:

WA16B7, Test1
1AAA42, Test2
5A5CC5, Test3

代码的基本要点应该是这样的,其中textLines是从文本文件中读取的。我只是不知道每个条件的正则表达式语法是否正确,这些语法仍然允许上面的文本,以及将它们按哪个顺序放置,以便在遇到时捕获它们。

if ! [[ $textLines =~ [A-Z0-9]{6}[[:space:]]*,+ ]]; then
echo "Error: A"
continue
fi
if ! [[ $textLines =~ [A-Z0-9]{6}[[:space:]]*,+ ]]; then
echo "Error: B"
continue
fi
if ! [[ $textLines =~ [A-Z0-9]{6}[[:space:]]*,+ ]]; then
echo "Error: C"
continue
fi

我使用了python。

文件

WA16B7,
1AAA42,
5A5CC5,
WA16B7
1AAA42
5A5CC5
WA16B7 Test1
1AAA42  Test2
5A5CC5   Test3
WA16B7, Test1
1AAA42, Test2
5A5CC5, Test3

编写脚本

import re
def test(text):
if re.search('w{6}, w{1,}', text):
return f'OK'
elif re.search('w{6}, ?',text):
return f'Erro 1'
elif re.search('w{6} ?',text):
return f'Erro 2'
with open(file='a.txt',mode='r') as input_file:
list_lines = input_file.read().splitlines()
for i in list_lines:
print(f'Result: {test(i)} | word: {i}')

结果

Result: Erro 1 | word: WA16B7,
Result: Erro 1 | word: 1AAA42,
Result: Erro 1 | word: 5A5CC5,
Result: Erro 2 | word: WA16B7
Result: Erro 2 | word: 1AAA42
Result: Erro 2 | word: 5A5CC5
Result: Erro 2 | word: WA16B7 Test1
Result: Erro 2 | word: 1AAA42  Test2
Result: Erro 2 | word: 5A5CC5   Test3
Result: OK | word: WA16B7, Test1
Result: OK | word: 1AAA42, Test2
Result: OK | word: 5A5CC5, Test3

最新更新