Get number from string with regular expression in java

in java, we use Pattern to compile a regular expression and do the match with Matcher.

Example1:

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

public class Test {

    public static void main(String args[]){
        String str = "12 gb";
        pickNumFromString(str);
    }
    private static void pickNumFromString(String str){
        String regEx = "//D+";
        Pattern pat = Pattern.compile(regEx);
        Matcher mat = pat.matcher(str);
        System.out.println(mat.replaceAll(""));
    }
}
 
Or, simply:

Example2:

    private static void pickNumFromString(String str){
        String regEx = "//D+";
       return str.replaceAll(regEx, "");
    }
}



To match Kafka real-time data with a regular expression in Java, you can use the following steps: 1. First, connect to your MySQL database using the JDBC driver. 2. Retrieve the Kafka real-time data from the Kafka topic. 3. Create a regular expression pattern using the java.util.regex.Pattern class. 4. Loop through the Kafka data and use the Matcher class to match the regular expression pattern with the data. 5. If the pattern matches, then you can insert the data into the MySQL table. Here's an example code snippet that demonstrates how to use regular expression matching with Kafka real-time data using Java: ```java import java.sql.*; import java.util.regex.*; public class KafkaRegexMatchExample { public static void main(String[] args) throws SQLException { String url = "jdbc:mysql://localhost:3306/mydatabase"; String username = "root"; String password = "password"; // Connect to MySQL database Connection connection = DriverManager.getConnection(url, username, password); // Retrieve Kafka real-time data // TODO: Implement Kafka consumer // Create regular expression pattern Pattern pattern = Pattern.compile("regex_pattern_here"); // Loop through Kafka data and match with pattern while (true) { String kafkaData = getKafkaData(); // Get Kafka data Matcher matcher = pattern.matcher(kafkaData); if (matcher.matches()) { // Insert data into MySQL table PreparedStatement statement = connection.prepareStatement("INSERT INTO mytable (column1, column2) VALUES (?, ?)"); statement.setString(1, matcher.group(1)); statement.setString(2, matcher.group(2)); statement.executeUpdate(); } } } private static String getKafkaData() { // TODO: Implement Kafka consumer logic to retrieve data } } ``` Note that this is just an example, and you'll need to modify it based on your specific requirements.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值