简体   繁体   English

如何使用正则表达式特定字符串拆分字符串

[英]How to split String using Regex specific String

I have a value(String) like "BLD00000001BLD00000002 BLD00000003, BLD00000004".我有一个值(字符串),例如“BLD00000001BLD00000002 BLD00000003,BLD00000004”。

I want to use Regex """^BLD\d{8}"""我想使用正则表达式"""^BLD\d{8}"""

but it didn't work..但它没有用..

I want to return results like (BLD00000001','BLD00000002','BLD00000003... )我想返回像 (BLD00000001','BLD00000002','BLD00000003...) 这样的结果

        var regex = Regex("""[\{\}\[\]\/?.,;:|\) *~`!^\-_+<>@\#$%&\\\=\(\'\"]""")
        val cvrtBldIds = bldIds.split(regex)

        if (cvrtBldIds.joinToString(separator="").length % 11 != 0) {
            throw BadRequestException("MSG000343", listOf("빌딩Id", "BLD[숫자8자리]"))
        } else {
            val res = cvrtBldIds
                .filter{it.startsWith("BLD")}   // BLD로 시작하는 것만 추출
                .joinToString(separator = "','")      // 아이디 앞뒤로 ',' 붙이기 
            bldIds = res
            var sb = StringBuffer()
            sb.append("'")
            sb.append(bldIds)
            sb.append("'")
            input.bldId = sb.toString()
        }

Do it as follows:执行以下操作:

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

public class Main {
    public static void main(String[] args) {
        String str = "BLD00000001BLD00000002 BLD00000003, BLD00000004";
        List<String> list = new ArrayList<String>();
        Pattern pattern = Pattern.compile("BLD\\d{8}");
        Matcher matcher = pattern.matcher(str);
        while (matcher.find()) {
            list.add(matcher.group());
        }
        System.out.println(list);
    }
}

Output: Output:

[BLD00000001, BLD00000002, BLD00000003, BLD00000004]

Notes:笔记:

  1. BLD\\d{8} means starting with BLD and then 8 digits. BLD\\d{8}表示以BLD开头,然后是 8 位数字。
  2. Java regex tutorial: https://docs.oracle.com/javase/tutorial/essential/regex/ Java 正则表达式教程: https://docs.oracle.com/javase/tutorial/essential/regex/

Seems you want to split on a space, or a comma-space combo, or between a digit and the text BLD .似乎您想在空格或逗号空格组合上或在数字和文本BLD之间进行拆分 The following regex can do that:以下正则表达式可以做到这一点:

,?\s|(?<=\d)(?=BLD)

See regex101 for demo.有关演示,请参见regex101

Here is how you can extract BLD\d{8} pattern matches in Kotlin using .findall() :以下是如何使用.findall()在 Kotlin 中提取BLD\d{8}模式匹配:

val text = """"BLD00000001BLD00000002 BLD00000003, BLD00000004"."""
val matcher = """BLD\d{8}""".toRegex()
println(matcher.findAll(text).map{it.value}.toList() )
// => [BLD00000001, BLD00000002, BLD00000003, BLD00000004]

See the Kotlin demo请参阅Kotlin 演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM