返回
正则表达式教程:Linux 文件夹路径验证
正则表达式
2024-02-28 15:49:31
一、正则解释
正则表达式:/^/(?:[^/]+/)*$/
模式解释:
- ^: 匹配字符串的开始。
- /: 匹配正斜杠(/)。
- (?:[^/]+/): 匹配一个或多个非正斜杠字符,后面紧跟一个正斜杠。
- *: 匹配前一个元素零次或多次。
- $: 匹配字符串的结束。
整体含义: 该正则表达式匹配一个字符串,该字符串以正斜杠开头,后面是零个或多个非正斜杠字符和正斜杠组成的路径,并以正斜杠结尾。
二、使用场景
此正则表达式用于验证 Linux 文件夹路径的格式是否正确,确保路径符合以下规则:
- 以正斜杠开头。
- 可以包含一个或多个文件夹名称,每个文件夹名称后面都跟一个正斜杠。
- 以正斜杠结尾。
三、代码示例
JavaScript:
const regex = /^\/(?:[^/]+\/)*$/;
const testPaths = ['/usr/ad/dd/', '/', '/root/', '/ a a / a / a a /'];
testPaths.forEach(path => {
console.log(`Path: ${path}, Valid: ${regex.test(path)}`);
});
Java:
import java.util.regex.Pattern;
public class LinuxPathValidator {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^/(?:[^/]+/)*import java.util.regex.Pattern;
public class LinuxPathValidator {
public static void main(String[] args) {
Pattern pattern = Pattern.compile("^/(?:[^/]+/)*$");
String[] testPaths = {"/usr/ad/dd/", "/", "/root/", "/ a a / a / a a /"};
for (String path : testPaths) {
System.out.println("Path: " + path + ", Valid: " + pattern.matcher(path).matches());
}
}
}
quot;);
String[] testPaths = {"/usr/ad/dd/", "/", "/root/", "/ a a / a / a a /"};
for (String path : testPaths) {
System.out.println("Path: " + path + ", Valid: " + pattern.matcher(path).matches());
}
}
}
PHP:
<?php
$regex = '/^\/(?:[^/]+\/)*$/';
$testPaths = ['/usr/ad/dd/', '/', '/root/', '/ a a / a / a a /'];
foreach ($testPaths as $path) {
echo "Path: $path, Valid: " . (preg_match($regex, $path) ? 'true' : 'false') . '<br>';
}
Python:
import re
regex = r"^\/(?:[^/]+\/)*import re
regex = r"^\/(?:[^/]+\/)*$"
testPaths = ['/usr/ad/dd/', '/', '/root/', '/ a a / a / a a /']
for path in testPaths:
print("Path:", path, ", Valid:", re.match(regex, path))
quot;
testPaths = ['/usr/ad/dd/', '/', '/root/', '/ a a / a / a a /']
for path in testPaths:
print("Path:", path, ", Valid:", re.match(regex, path))
输出:
Path: /usr/ad/dd/, Valid: true
Path: /, Valid: true
Path: /root/, Valid: true
Path: / a a / a / a a /, Valid: false