检查字符串不应以 space 开头或结尾且不应以点 (.)

Regex that checks that a string should not start or end with a space and should not end with a dot (.)

根据要求,我需要生成一个正则表达式来匹配不以 space 开头或结尾的字符串。除此之外,字符串不应以特殊字符点 (.) 结尾。根据我的理解,我生成了一个正则表达式 "\S(.*\S)?$",它限制了在字符串的开头和结尾有一个 space 的字符串。使用此表达式,我需要验证以点结尾的字符串的正则表达式。任何形式的帮助将不胜感激。

使用以下正则表达式

^\S.*[^.\s]$

Regex explanation here


如果你想匹配单个字符那么你可以使用look-ahead and look behind-assertion.

^(?=\S).+(?<=[^.\s])$

Regex explanation here


如果look-behind不支持则使用

^(?=\S).*[^.\s]$

Regex explanation here

您可以使用模式:^[^\ ].*[^\ .]$

这里有一个演示:

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

public class Main {

    public static void main(String[] args) {
        List<String> list = new ArrayList<>();
        list.add(" This string starts with a space");
        list.add("This string ends with a space ");
        list.add("This string ends with a dot.");
        list.add("This string ends with a newline\n");
        list.add("\tThis string starts with a tab character");

        Pattern p = Pattern.compile("^[^\ ].*[^\ .]$");

        for (String s : list) {
            Matcher m = p.matcher(s);
            if (m.find())
                System.out.printf("\"%s\" - Passed!\n", s);
            else
                System.out.printf("\"%s\" - Didn't pass!\n", s);
        }
    }
}

这会产生:

" This string starts with a space" - Didn't pass!
"This string ends with a space " - Didn't pass!
"This string ends with a dot." - Didn't pass!
"This string ends with a newline
" - Passed!
"   This string starts with a tab character" - Passed!