gpt4 book ai didi

Java 正则表达式 : check is a string has specific structure: *test_text*

转载 作者:行者123 更新时间:2023-12-02 09:31:27 24 4
gpt4 key购买 nike

我该怎么做?我想要一个像这样的字符串

*test_text*

被识别为模式字符串,但是像这样的字符串:

*test____text*

*test_*[text*

或者 *test_again_text*不被认可

最佳答案

我猜想这里可能需要这个表达式:

(?i)^\*[a-z0-9]+_[a-z0-9]+\*$

测试

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


public class re{

public static void main(String[] args){

final String regex = "(?i)^\\*[a-z0-9]+_[a-z0-9]+\\*$";
final String string = "*test_text*\n"
+ "*test____text*\n"
+ "*test_*[text*\n"
+ "*test_again_tex";

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

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

}
}

输出

Full match: *test_text*
<小时/>

如果您想简化/修改/探索表达式,regex101.com 的右上角面板已对此进行了解释。 。如果您愿意,也可以在 this link 观看,它如何与一些示例输入相匹配。

<小时/>

Demo 2

关于Java 正则表达式 : check is a string has specific structure: *test_text*,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57931548/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com