[英]Java regex expression to include underscore
I am trying with the below line, which ignores underscore but I want to change it to include underscore. 我正在尝试使用以下行,该行会忽略下划线,但我想将其更改为包括下划线。
String name = "$SF_Update$";
String regexp = "\\$(.*?)(?:[\\_].*)?\\$"; // want to change this line
Pattern pattern = Pattern.compile(regexp);
Matcher matcher = pattern.matcher(name);
I tried the below options: 我尝试了以下选项:
String regexp ="\\$([a-zA-Z]+(?:_[a-zA-Z]+)*)\\$"
It includes underscore but it is considering the next line strings which doesn't have a $ at the end as well, like: "$SF_Update$" "$SF_Updateone" Please provide a solution. 它包括下划线,但它也在考虑在末尾也没有$的下一行字符串,例如:“ $ SF_Update $”“ $ SF_Updateone”请提供解决方案。
Code: 码:
String str1 = "$SF_Update$";
String str2 = "$SF_Update_One$";
String str3 = "$SF_Update_One";
Pattern pattern = Pattern.compile("\\$([^_]+_{1}[^_]+)\\$");
Matcher matcher1 = pattern.matcher(str1);
Matcher matcher2 = pattern.matcher(str2);
Matcher matcher3 = pattern.matcher(str3);
if (matcher1.matches())
System.out.println(str1 + " => " + matcher1.group(1));
else
System.out.println(str1 + " => " + "No Match.");
if (matcher2.matches())
System.out.println(str2 + " => " + matcher2.group(1));
else
System.out.println(str2 + " => " + "No Match.");
if (matcher3.matches())
System.out.println(str3 + " => " + matcher3.group(1));
else
System.out.println(str3 + " => " + "No Match.");
Output: 输出:
$SF_Update$ => SF_Update
$SF_Update_One$ => No Match.
$SF_Update_One => No Match.
Try with this expresion: 试试这个表达式:
\$[A-Za-z]+(_[A-Za-z]+)*\$
I do it in Regex Online 我在Regex Online中进行
And if the name could have numbers: 如果名称可以包含数字:
\$[A-Za-z0-9]+(_[A-Za-z0-9]+)*\$
And it rules for me. 它为我统治。
If you want to capture everything between $ and assert that underscore is present use this regex: 如果要捕获$之间的所有内容并断言下划线存在,请使用此正则表达式:
\\$(.*?)_([^_]*)\\$
(.*?)
matches one symbol and next it tries to match underscore. (.*?)
匹配一个符号,然后下一个匹配下划线。 If it doesn't, (.*?)
matches this symbol and regex tries to match underscore again. 如果不是,则
(.*?)
与此符号匹配,而正则表达式会尝试再次匹配下划线。
After underscore is matched, ([^_]*)
matches everything that is not underscore for 0 or more times. 下划线匹配后,
([^_]*)
匹配0次或多次不下划线的所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.