Search code examples
javaregexstring-matching

How to use regex for a single character in a String?


I have the following String :

LoopStep(i,0,m-1,1) 

and I want to use regex so that I will find just the first "(" ,for example my regex code is : \\([^)]*\\). I want to check for the 1st open parenthesis only so I don't have a problem with this code:

LoopStep ((i,0,m-1,1)).

Solution

  • If you only want to check on whether your String doesn't contain two consecutive parenthesis, you can use indexOf or contains instead of regular expressions:

    // will return true only if the String doesn't contain ((
    // you can also use to infer actual index
    test.indexOf("((") == -1
    // same and better but you can't use the index
    !test.contains("((")
    

    Note that here, test is your desired String variable, e.g. with value "LoopStep(i,0,m-1,1)".

    If you're actually parsing a syntax, which appears to be the case, do not use regular expressions.

    You will likely have to build your own parser in order to verify and parse the syntax of your meta-language.

    Note

    Just to give you a glimpse of what mess you might be getting into if you use regular expressions to validate the syntax in this case, here's a regex example matching your whole String to check against consecutive parenthesis ("(("):

    //           | non-parenthesis
    //           |    | or
    //           |    | | not preceded by parenthesis
    //           |    | |      | actual parenthesis
    //           |    | |      |  | not followed by parenthesis
    //           |    | |      |  |       | 1+ length(adjust with desired quantifier)
    test.matches("([^(]|(?<!\\()\\((?!=\\())+")