【问题标题】:Regex that checks that a string should not start or end with a space and should not end with a dot (.)正则表达式检查字符串不应以空格开头或结尾且不应以点 (.)
【发布时间】:2016-09-26 12:59:43
【问题描述】:

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

【问题讨论】:

  • 表示字符串不应以空格或...right??结尾
  • 您使用哪种编程语言?
  • 感谢您的快速回复。我在java中工作。
  • ^\S.*[^.\s]$....
  • THnaks Pranav 成功了

标签: regex space


【解决方案1】:

使用下面的正则表达式

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

Regex explanation here


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

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

Regex explanation here


如果后视不支持则使用

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

Regex explanation here

【讨论】:

  • /^\S.*[^.\s]$ / 这很好,但至少需要一个字符才能通过(即不适用于验证至少一个字符,没有尾随或前导空格)
【解决方案2】:

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

这是一个演示:

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!

【讨论】:

    猜你喜欢
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-07-04
    相关资源
    最近更新 更多