Java如何使用正则表达式从字符串中提取字符串或数字呢?
下文笔者讲述Java代码从字符串中提取字符串和数字的方法及示例分享
从字符串中提取字符串和数字的实现思路: 定义合适的正则表达式,然后提取符合条件的数据
例1:提取一次不同内容
package com.example.a; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String[] args) { String line = "This order was aabbcc placed for QT3000! OK?"; String regex = "(\\D*)(\\s+)(aa\\S+)(\\D*)(\\d+)(.*)"; // 创建 Pattern 对象 Pattern pattern = Pattern.compile(regex); // 现在创建 matcher 对象 Matcher m = pattern.matcher(line); if (m.find()) { System.out.println("group0: " + m.group(0)); System.out.println("group1: " + m.group(1)); System.out.println("group2: " + m.group(2)); System.out.println("group3: " + m.group(3)); System.out.println("group3: " + m.group(4)); System.out.println("group3: " + m.group(5)); System.out.println("group3: " + m.group(6)); } } } ----运行以上代码,将输出以下信息----- group0: This order was aabbcc placed for QT3000! OK? group1: This order was group2: group3: aabbcc group3: placed for QT group3: 3000 group3: ! OK?
例2:提取多次相同内容
package com.example.a; import java.util.regex.Matcher; import java.util.regex.Pattern; public class Demo { public static void main(String[] args) { Pattern pattern = Pattern.compile("(LM\\d+)"); String str = "张三[LM89652] 李四[LM12365] 王五[LM56856]"; Matcher matcher = pattern.matcher(str); while (matcher.find()) { System.out.println(matcher.group(1)); } } } -----运行以上代码,将输出以下信息---- LM89652 LM12365 LM56856 Matcher详解
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。