简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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