正则表达式,用于检查字符串不应以空格开头或结尾,并且不应以点(。)结尾

时间:2016-05-28 06:56:21

标签: regex space

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

2 个答案:

答案 0 :(得分:4)

使用以下正则表达式

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

Regex explanation here

Regular expression visualization

如果您想匹配单个字符,则可以使用look-ahead and look behind-assertion

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

Regex explanation here

Regular expression visualization

如果后视不支持,请使用

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

Regex explanation here

Regular expression visualization

答案 1 :(得分:0)

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

这是一个演示:

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!