我有大量的正则表达式需要检查,它们以 Java/JavaScript RegEx 格式输出,如下所示:
\d{7}|\d{8}
[a-zA-Z]\d{8}
[a-zA-Z]\d{3}-\d{3}-\d{2}-\d{3}\d[0|1]
鉴于我对 Bash 很熟悉,但有一些我可能从未想到的小技巧,我想知道是否有一种方法可以采用测试字符串来针对 RegEx 的这种特定格式进行评估。
我已经尝试了一些 grep 并使用我知道通过正则表达式测试器的数据进行评估 http://www.cyber-reality.com/regexy.html
在使用 bash RegEx 时,我可以正确地评估这些字符串,但是我无法将服务器将这些字符串输出的方式更改为我知道如何在 bash 中评估的格式。
有什么想法吗?
最佳答案
我建议编写一个命令行工具来进行检查。然后您可以从 bash 脚本调用此工具。
使用this starting point ,这里有一些可以满足您需要的东西:
import java.io.Console;
import java.util.regex.Pattern;
import java.util.regex.Matcher;
public class RegexTestHarness {
public static void main(String[] args) {
try{
Pattern pattern = Pattern.compile(args[1]);
Matcher matcher = pattern.matcher(args[2]);
boolean found = false;
while (matcher.find()) {
System.out.println(matcher.group() + ", position " + matcher.start() + ":" + matcher.end() + "\n");
found = true;
}
if (!found) {
System.out.println("\nNo match found.");
System.exit(1);
}
}
catch (Exception e) {
System.out.println("\nCaught an exception. Description: " + e.getMessage());
System.exit(2);
}
}
}
要检查是否有任何匹配,您可以使用以下脚本:
#!/bin/bash
if java RegexTestHarness "my_regex" "my_input_string"; then
echo "Expression matches"
else
echo "Expression doesn't match"
fi
要检查特定结果,您可以捕获命令的输出并在脚本中对其进行处理。
关于Bash 中的 Java 格式正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18517569/