1

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.

1

3 Answers 3

4

Use regex pattern

(?:(?<=[.])(?![0-9])|(?<=[?]))

str.split("(?:(?<=[.])(?![0-9])|(?<=[?]))");
Sign up to request clarification or add additional context in comments.

2 Comments

Wow! Thanks this one does work! Can you tell me why mine didn't work?
@JouiCK - (1) there should not be a period in your negative lookahead; (2) should not apply negative lookahead for ?; (3) should have lookahead out of lookbehind (recommended)
2

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.

3 Comments

like this? (?<=(?!\\.[0-9])[?\\.])
it doesn't work either on Android but it does in the java program, on my computer.
Yes, strictly speaking you don't need the \\ inside the [?.] but I don't think it does any harm.
1

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

2 Comments

This one seems to work but it doesn't return the "." at the end like Omega's one. Thank you anyway! :)
The one at the end is easily appendable.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.