正規表現で文字列を検索後、条件に一致した部分以外を削除する

Pythonの例:

import re

text = "This is a sample text with some numbers: 1234 and 5678."

# 正規表現で数字を検索
pattern = r"\d+"
matches = re.findall(pattern, text)

# 数字以外の部分を削除
new_text = re.sub(f"[^{pattern}]", "", text)

print(new_text)  # "12345678"

Javaの例:

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {
    public static void main(String[] args) {
        String text = "This is a sample text with some numbers: 1234 and 5678.";

        // 正規表現で数字を検索
        String pattern = "\\d+";
        Pattern p = Pattern.compile(pattern);
        Matcher m = p.matcher(text);

        // 数字以外の部分を削除
        StringBuilder sb = new StringBuilder();
        while (m.find()) {
            sb.append(m.group());
        }
        String new_text = sb.toString();

        System.out.println(new_text);  // "12345678"
    }
}

JavaScriptの例:

let text = "This is a sample text with some numbers: 1234 and 5678.";

// 正規表現で数字を検索
let pattern = /\d+/g;
let matches = text.match(pattern);

// 数字以外の部分を削除
let new_text = text.replace(new RegExp(`[^${pattern}]`, "g"), "");

console.log(new_text);  // "12345678"

コメント

タイトルとURLをコピーしました