简体   繁体   中英

Regex to find all characters before and after first underscore, then make sure they are the same

I have these two strings

2014_UMW
2014_UMW_web

I need to write a regex to get the character before and after the fist underscore. Then I need to make sure that they are both the same. I am checking to make sure that 2014_UMW is at the beginning of both strings. 2014_UMW is only one example. It could be 2015_YYY and 2015_YYY_web etc.

This the is regex that I am using (?<=_)[^_]+(?=_) and then I am using pattern and matcher methods to see if they are both the same, but it is not working right. I have also tried this regex [a-zA-Z_0-9]+[^_]+(?=_) .

To get the part after first _ you can use this regex:

Pattern p = Pattern.compile("^[^_]+_([^_]+)");

and get the captured group #1 using matcher.group(1) for the part your're interested in.

RegEx Demo

The pattern you say you are using, (?<=_)[^_]+(?=_) , matches a non-empty sequence of characters other than '_' that is bounded on each side by an underscore. That's nothing like your intent to "get the character before and after the [first] underscore".

From your example, I think what you mean to do is split the strings at underscores, and compare the first two segments of each. In that case, you might consider using String.split() . Details could vary depending on exactly how you want to characterize the splitting, but here's one, simple, way it might go:

String[] parts1 = string1.split("_");
String[] parts2 = string2.split("_");
// compare elements of parts1 and parts2

Alternatively, if you want to use a regex to capture the first two segments of such a string, then you want a Pattern along these lines:

Pattern p = Pattern.compile("^([^_]+)_([^_]+)(?:_.*)?");

(That form is suitable for use with any of Matcher.matches() , Matcher.find() , or Matcher.lookingAt() ; simpler forms are possible if you only want to support one or both of the latter two.) Again, details of the needed pattern may vary depending on exactly what you're after.

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