简体   繁体   English

正则表达式仅允许单词之间使用单个分隔符

[英]Regex that allows only single separators between words

I need to construct a regular expression such that it should not allow / at the start or end, and there should not be more than one / in sequence. 我需要构造一个正则表达式,使得它不应在开始或结束处使用/ ,并且顺序中不得超过一个/

Valid Expression is: AB/CD
Valid Expression   :AB
Invalid Expression:  //AB//CD//
Invalid Expression:  ///////
Invalid Expression:  AB////////

The / character is just a separator between two words. /字符只是两个单词之间的分隔符。 Its length should not be more than one between words. 字之间的长度不得超过一。

[a-zA-Z]+(/[a-zA-Z]+)+

It matches 它匹配

a/b
a/b/c
aa/vv/cc

doesn't matches 不匹配

a
/a/b
a//b
a/b/

Demo 演示版

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Reg {
    public static void main(String[] args) {
    Pattern pattern = Pattern.compile("[a-zA-Z]+(/[a-zA-Z]+)+");
    Matcher matcher = pattern.matcher("a/b/c");
    System.out.println(matcher.matches());
    }
}

This regex does it: 这个正则表达式可以做到这一点:

^(?!/)(?!.*//).*[^/]$

So in java: 所以在java中:

if (str.matches("(?!/)(?!.*//).*[^/]"))

Note that ^ and $ are implied by matches() , because matches must match the whole string to be true. 请注意, matches()暗示^和$,因为匹配必须匹配整个字符串才是true。

Assuming you only want to allow alphanumerics (including underscore) between slashes, it's pretty trivial: 假设您只想在斜线之间允许字母数字(包括下划线),那就太简单了:

boolean foundMatch = subject.matches("\\w+(?:/\\w+)*");

Explanation: 说明:

\w+  # Match one or more alnum characters
(?:  # Start a non-capturing group
 /   # Match a single slash
 \w+ # Match one or more alnum characters
)*   # Match that group any number of times

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

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