仅匹配字符串的第一个和最后一个字符

时间:2011-07-08 06:35:26

标签: java regex

我查看了其他 stackoverflow 问题,找不到问同一个问题的问题,所以这里是:

如何匹配字符串的第一个和最后一个字符(可以是多行或空格)。

例如:

String = "this is a simple sentence"

请注意,该字符串包含开始和结束引号。

如何匹配字符串以引号(“)开头和结尾的第一个和最后一个字符。

我试过了:

^"|$" and \A"\Z"

但这些不会产生预期的结果。

提前感谢您的帮助:)

4 个答案:

答案 0 :(得分:3)

这是你在找什么?

String input = "\"this is a simple sentence\"";
String result = input.replaceFirst("(?s)^\"(.*)\"$", " $1 ");

如果输入字符串的第一个和最后一个字符以"开头和结尾,则它将用空格替换。它也可以跨多行工作,因为DOTALL标志由(?s)指定。

答案 1 :(得分:2)

匹配整个输入".*"的正则表达式。在java中,它看起来像这样:

String regex = "\".*\"";
System.out.println("\"this is a simple sentence\"".matches(regex)); // true
System.out.println("this is a simple sentence".matches(regex));     // false
System.out.println("this is a simple sentence\"".matches(regex));   // false

如果您想删除引号,请使用:

String input = "\"this is a simple sentence\"";
input = input.replaceAll("(^\"|\"$)", "")); // this is a simple sentence (without any quotes)

如果您希望这可以在多行上使用,请使用:

String input = "\"this is a simple sentence\"\n\"and another sentence\"";
System.out.println(input + "\n");
input = input.replaceAll("(?m)(^\"|\"$)", "");
System.out.println(input);

产生输出:

"this is a simple sentence"
"and another sentence"

this is a simple sentence
and another sentence

正则表达式(?m)(^"|"$)的解释:

  • (?m)表示“正则表达式其余部分的换行符之前和之前的插入符号和美元匹配”
  • (^"|"$)表示^""$,表示“行首,然后是双引号”或“双引号然后结束行”

答案 2 :(得分:0)

为什么不使用基于String的charAt方法获取第一个和最后一个字符的简单逻辑?对空/不完整的字符串进行一些检查,你应该完成。

答案 3 :(得分:0)

String regexp = "(?s)\".*\"";
String data = "\"This is some\n\ndata\"";
Matcher m = Pattern.compile(regexp).matcher(data);
if (m.find()) {
    System.out.println("Match starts at " + m.start() + " and ends at " + m.end());
}
相关问题