如何使用正则表达式选择字符串格式化的值

huangapple go评论75阅读模式
英文:

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 = &quot;Today is (\\w+) with degree (\\d+)℉&quot;;
final String string = &quot;Today is Sunday with degree 70℉&quot;;

final Pattern pattern = Pattern.compile(regex, Pattern.MULTILINE | Pattern.UNICODE_CHARACTER_CLASS);
final Matcher matcher = pattern.matcher(string);

while (matcher.find()) {
    System.out.println(&quot;Full match: &quot; + matcher.group(0));
    for (int i = 1; i &lt;= matcher.groupCount(); i++) {
        System.out.println(&quot;Group &quot; + i + &quot;: &quot; + matcher.group(i));
    }
}

huangapple
  • 本文由 发表于 2020年8月20日 15:33:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/63500349.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定