Does anyone have the source for a GetBetweenAll function for Java?
Java GetBetweenAll?
#1
Posted 27 September 2014 - 03:37 PM
#2
Posted 27 September 2014 - 05:51 PM
Java sucks when it comes to manipulating strings. Your best bet would be the java.util.regex API.
As a word of caution, I would avoid testing your regexes in Python or Javascript first because each language does regex a bit differently so even if it works in one, it might not work in another.
#3
Posted 28 September 2014 - 02:25 AM
public static String[] arrGetBetweenM;
public static void GetBetweenM(String strString, String strStart, String strEnd, int intMatches) {
arrGetBetweenM = new String[intMatches];
int lngPosition = 1;
for (int i = 0; i < intMatches; i++) {
int intBegin = strString.indexOf(strStart, lngPosition) + strStart.length();
lngPosition = intBegin + 1;
int intEnd = strString.indexOf(strEnd, lngPosition);
arrGetBetweenM[i] = strString.substring(intBegin, intEnd);
}
}Use:
Class.GetBetweenM(Dpage, "<", ">", i);
System.out.println(Class.arrGetBetweenM[i]);
Where input i (amount of matches) is output 0 to i - 1.
#4
Posted 28 September 2014 - 09:34 AM
I searched this forum high and low for that! I remember seeing it years ago but couldn't find it again. Thanks, @Waser Lave.
Thanks @Kway. I've been programming for years so I know all about regex . I just wanted to see if I could avoid reinventing the wheel. Thanks though!
Edited by Riku, 28 September 2014 - 09:45 AM.
#5
Posted 22 October 2014 - 03:10 PM
If you wanted to use Regex and pattern matching, you could do something like the following:
public static List<String> GetBetween(String start, String end, String source) { List<String> results = new ArrayList(); Pattern p = Pattern.compile(start + "(.*?)" + end); Matcher m = p.matcher(source); while (m.find()) { results.add(m.group(1)); } return results; }
If you still wanted limits you could do something such as :
public static List<String> GetBetween(String start, String end, String source) { return GetBetween(start, end, source, -1); } public static List<String> GetBetween(String start, String end, String source, int limit) { int count = 0; List<String> results = new ArrayList(); Pattern p = Pattern.compile(start + "(.*?)" + end); Matcher m = p.matcher(source); while (m.find() && (limit == -1 || count < limit)) { results.add(m.group(1)); count++; } return results; }
0 user(s) are reading this topic
0 members, 0 guests, 0 anonymous users