Joni

repository·master·Indexed 41 days ago

https://github.com/jruby/joni

A Java port of the Oniguruma regular expression library that provides advanced regex capabilities using byte arrays and specific encodings.

Tokens
870
Snippets
3
Records
3
Agent score
2%

What's inside Joni

  1. Perform basic regex matching with Joni

    master

    To perform a regex match, create a Regex object using a byte array pattern, an offset, a length, an Option, and an encoding (typically UTF8Encoding.INSTANCE). Then, create a Matcher from that regex and use matcher.search() to find the pattern within a target byte array. search() returns the starting index of the match, or -1 if no match is found.

    byte[] pattern = "a*".getBytes();
    byte[] str = "aaa".getBytes();
    
    Regex regex = new Regex(pattern, 0, pattern.length, Option.NONE, UTF8Encoding.INSTANCE);
    Matcher matcher = regex.matcher(str);
    int result = matcher.search(0, str.length, Option.DEFAULT);
  2. Access named capture groups

    master

    To use named captures, define them in your pattern using the (?<name>...) syntax. After a successful match, iterate through the named backreferences using regex.namedBackrefIterator(). Each NameEntry in the iterator provides access to the capture group numbers via e.getBackRefs(). You can then use these numbers to look up the start and end positions in the Region object obtained from the matcher.

    byte[] pattern = "(?<name>a*)".getBytes();
    byte[] str = "aaa".getBytes();
    
    Regex regex = new Regex(pattern, 0, pattern.length, Option.NONE, UTF8Encoding.INSTANCE);
    Matcher matcher = regex.matcher(str);
    int result = matcher.search(0, str.length, Option.DEFAULT);
    if (result != -1) {
        Region region = matcher.getEagerRegion();
        for (Iterator<NameEntry> entry = regex.namedBackrefIterator(); entry.hasNext();) {
            NameEntry e = entry.next();
            int number = e.getBackRefs()[0]; // can have many refs per name
            // int begin = region.beg[number];
            // int end = region.end[number];
        }
    }
  3. Access capture groups using Region

    master

    When a match is successful (i.e., matcher.search() does not return -1), you can access the captured sub-expressions using matcher.getEagerRegion(). This returns a Region object containing the start and end indices for the captured groups.

    byte[] pattern = "(a*)".getBytes();
    byte[] str = "aaa".getBytes();
    
    Regex regex = new Regex(pattern, 0, pattern.length, Option.NONE, UTF8Encoding.INSTANCE);
    Matcher matcher = regex.matcher(str);
    int result = matcher.search(0, str.length, Option.DEFAULT);
    if (result != -1) {
        Region region = matcher.getEagerRegion();
    }