Reputation: 1402
I'm trying to split a string at every "." or "?" and I use this regular expression:
(?<=(?!.[0-9])[?.])
In theory the code also prevents splitting if the point is followed by a number so things like 3.000 are not split and it also includes the point in the new string.
For example if I have this text: "Hello. What's your favourite number? It's 3.560." I want to get thi: "Hello.","What's your favourite number?","It's 3.560."
I've made a simple java program on my computer and it works exactly like I want:
String[] x = c.split("(?<=(?!.[0-9])[?.])");
for(String v : x){
System.out.println(v);
}
However when I use this same regex in my Android app it doesn't split anything...
x = txt.split("(?<=(?!.[0-9])[?.])");
//This, in my android app, returns an array with only one entry which is the whole string without splitting.
PS. Using (?<=[?.]) works so the problem must be in the (?!.[0-9]) part which is meant to exclude points followed by a number.
Upvotes: 1
Views: 3259
Reputation: 11940
Try this.
public class Tester {
public static void main(String[] args){
String regex = "[?.][^\\d]";
String tester = "Testing 3.015 dsd . sd ? sds";
String[] arr = tester.split(regex);
for (String s : arr){
System.out.println(s);
}
}
}
Output:
Testing 3.015 dsd
sd
sds
Upvotes: 1
Reputation: 43663
Use regex pattern
(?:(?<=[.])(?![0-9])|(?<=[?]))
str.split("(?:(?<=[.])(?![0-9])|(?<=[?]))");
Upvotes: 4
Reputation: 122364
Remember that outside a square bracket character class, .
in a regular expression means any single character. You need \.
to match a literal dot, which in turn means you need \\.
in the string literal.
Upvotes: 2