英文:
How to pick string formatter value by using regex
问题
有一个带有格式的字符串:
`今天是 %s,气温为 %d℉。`
如何使用 Java 中的正则表达式提取 %s 值和 %d 值?
例如:
```java
输入:今天是星期日,气温为 70℉
输出:星期日,70
<details>
<summary>英文:</summary>
There is a string with formatter:
`Today is %s with degree %d℉.`
How can I pick %s value and %d value by using regex in java?
For Example:
Input: Today is Sunday with degree 70℉
Output: Sunday, 70
</details>
# 答案1
**得分**: 1
这里有一个 [Java 示例](https://regex101.com/r/BFBg6I/1):
```java
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "今天是 (\\w+),气温 (\\d+)℉";
final String string = "今天是星期日,气温 70℉";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.UNICODE_CHARACTER_CLASS);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("完整匹配: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("第 " + i + " 组: " + matcher.group(i));
}
}
英文:
Here is a java example:
import java.util.regex.Matcher;
import java.util.regex.Pattern;
final String regex = "Today is (\\w+) with degree (\\d+)℉";
final String string = "Today is Sunday with degree 70℉";
final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.UNICODE_CHARACTER_CLASS);
final Matcher matcher = pattern.matcher(string);
while (matcher.find()) {
System.out.println("Full match: " + matcher.group(0));
for (int i = 1; i <= matcher.groupCount(); i++) {
System.out.println("Group " + i + ": " + matcher.group(i));
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论