【问题标题】:I'm trying to learn about Regular Expressions我正在尝试学习正则表达式
【发布时间】:2018-07-05 22:22:24
【问题描述】:

1.基于此代码https://docs.oracle.com/javase/tutorial/essential/regex/test_harness.html

谁能解释一下这个 \"%s\" in

while (matcher.find()) {
        console.format("I found the text" + " \"%s\" starting at " +
        "index %d and ending at index %d.%n",
        matcher.group(),
        matcher.start(),
        matcher.end());
        found = true;
}

我只知道%s 是字符串。

2.引用元字符https://docs.oracle.com/javase/tutorial/essential/regex/literals.html这个输出有什么解释吗?

【问题讨论】:

  • %s 一个格式化字符,用于基于格式的打印,与正则表达式本身无关。 APIhere.

标签: java pattern-matching metacharacters


【解决方案1】:

String 中的百分号 (%) 与字母 b、c、d、e、f、s 的组合用于限制要显示的字符数。

%b- 布尔值
%c- 字符
%d- 整数
%e- 科学计数法
%f- 浮点数(双精度,浮点数)
%s- 字符串

例如:

String text = "abcdef";
System.out.printf("%.3s", text); //output:  abc

String text = "\"abcdef\"";
System.out.printf("%.3s", text); //output:  "ab

【讨论】:

  • 顺便说一句,它是 "%.3s" 。无论如何谢谢。
【解决方案2】:

\"%s\" 表示您想在两个引号之间放置一个字符串,例如结果可以是:

I found the text "some string"
//""-------------^           ^
// %s             ^_________^

%s 用于字符串,如果你想使用数字可以使用%d 等等

在 Java 中应该转义引号 如何? 你可以使用反斜杠 \" 所以考虑我有一个包含这样的引号的字符串 Hello "World" 如何在 Java 中将其用作字符串:

String string = "Hello "World"";  //<<------- this is an error syntax

要解决它,您必须转义引号:

String string = "Hello \"World\"";
                       ^      ^

看看https://docs.oracle.com/javase/8/docs/api/java/util/Formatter.html

【讨论】:

  • 两个反斜杠是干什么用的?
  • 他们转义了引号 (")。你可以删除它们,你会看到你得到了什么错误。
  • @Jérôme 你会得到java.lang.RuntimeException: Uncompilable source code - not a statement
  • 非常感谢@YCF_L 你能给我推荐一些可以学习特定主题的网站吗?
猜你喜欢
  • 2010-09-05
  • 1970-01-01
  • 2022-11-28
  • 2013-02-17
  • 1970-01-01
  • 1970-01-01
  • 2016-08-31
  • 2023-04-09
相关资源
最近更新 更多