Showing posts with label regex. Show all posts
Showing posts with label regex. Show all posts

Get Start End Offset of Named Group in JDK7


The Problem
We want to know the start and end offset of named group, but Matcher start(), end() in JDK 7 doesn't accept group name as its parameter.

JDK7 adds the support of Named Group:
(1) (?<NAME>X) to define a named group NAME".
(2) \\k<Name> to backref a named group "NAME"                   
(3) <$<NAME> to reference to captured group in matcher's replacement str 

We can use matcher.group(String NAME) to return the captured input subsequence by the given "named group", but its start(), end() in matcher doesn't accept group name as its parameter.

The Solution
Check the JDK code, look at how mathcer.group(String name) is implemented:
public String group(String name) {
    if (name == null)
        throw new NullPointerException("Null group name");
    if (first < 0)
        throw new IllegalStateException("No match found");
    if (!parentPattern.namedGroups().containsKey(name))
        throw new IllegalArgumentException("No group with name <" + name + ">");
    int group = parentPattern.namedGroups().get(name);
    if ((groups[group*2] == -1) || (groups[group*2+1] == -1))
        return null;
    return getSubSequence(groups[group * 2], groups[group * 2 + 1]).toString();
}
It uses int group = parentPattern.namedGroups().get(name) to get the group position of the named group. Check the pattern code: its namedGroups is not public: it's package visible only.
Map<String, Integer> namedGroups() {
    if (namedGroups == null)
        namedGroups = new HashMap<>(2);
    return namedGroups;
}
We can't call it directly, but we can use Java reflection to call this package visible method.

public void testGetNamedGrpupPositionInJDK7() throws Exception {
  Pattern pattern = Pattern.compile("((?<capture>abc).*d)(ef)");
  Integer groupPos = getNamedGrpupPositionInJDK7(pattern, "capture");
  if (groupPos == null) {
    System.out
        .println("Doesn't contain named group: capture, the pattern: "
            + pattern.toString());
  }
  Matcher matcher = pattern.matcher("abcxxdef");
  while (matcher.find()) {
    String matchedText = matcher.group("capture");
    matchedText = matcher.group(groupPos);
    System.out.println(matchedText + " " + matcher.start(groupPos)
        + ":" + matcher.end(groupPos));
  }
}

@SuppressWarnings("unchecked")
// don't use int, it would throw NPE if the regex doesn't contain the named
// group
private Integer getNamedGrpupPositionInJDK7(Pattern pattern,
    String namedGroup) throws NoSuchMethodException,
    IllegalAccessException, InvocationTargetException {
  Method namedGroupsMethod = Pattern.class.getDeclaredMethod(
      "namedGroups", null);
  namedGroupsMethod.setAccessible(true);

  Map<String, Integer> namedGroups = (Map<String, Integer>) namedGroupsMethod
      .invoke(pattern, null);
  return namedGroups.get(namedGroup);
}
Get Start End Offset of Named Group in JDK8
JDK8 realized this problem and added APIs: start(String groupName), end(String groupName) to get start and end offset of named group.
public void testGetNamedGrpupPositionInJDK8() throws Exception {
  Pattern pattern = Pattern.compile("((?<capture>abc).*d)(ef)");
  Matcher matcher = pattern.matcher("abcxxdef");
  while (matcher.find()) {
    // if the regex doesn't contain the named group, it would throw
    // IllegalArgumentException: No group with name <capture>
    System.out.println(matcher.group("capture") + " "
        + matcher.start("capture") + ":" + matcher.end("capture"));
  }
}
References
Named Capturing Group in JDK7 RegEx

Java Regex Practice: Using Backreferences and Named Group


Recently, I need write one regular expression to validate SSN for our UIMA related project.
I found this article Validating Social Security Numbers through Regular Expressions
^(?!219-09-9999|078-05-1120)(?!666|000|9\d{2})\d{3}-(?!00)\d{2}-(?!0{4})\d{4}$
^(?!219099999|078051120)(?!666|000|9\d{2})\d{3}(?!00)\d{2}(?!0{4})\d{4}$

The regex I need is a little different: the ssn must be separated by dash or one space.

Using Backreferences
The first separator can be dash or space, but the second separator has to be same. This is exactly where we should use backreferences, which repeats the text previous pattern matches.
(?!219-09-9999|078-05-1120)(?!666|000|9\\d{2})\\d{3}([- ])(?!00)\\d{2}\\1(?!0{4})(\\d{4})
\\1 here is to repeat the previous text matched bt pattern: ([- ])

Using Named Group
When the regex is complex, it's hard to figure out what \\1 refers to. Also we may change the regex in future, and may point \\1 to a different regex pattern by mistake.

We can use named group feature which is added in Java 7 to improve the regex's readability.
(1) (?X<NAME>) to define a named group NAME"  
(2) \\k<NAME>to backref a named group "NAME" 
(3) <$<NAME>to reference to captured group in matcher's replacement str 
(4) group(String NAME) to return the captured input subsequence by the given "named group"

The final regex is like below:
(?!219-09-9999|078-05-1120)(?!666|000|9\\d{2})\\d{3}(?<SEP>[- ])(?!00)\\d{2}\\k<SEP>(?!0{4})(\\d{4})
(?<SEP>[- ]) gives the pattern a name: SEP, \\k<SEP> refers to it.

Java Code
@Test
  public void regexBackReference() {
    String pStr = "(?!219-09-9999|078-05-1120)(?!666|000|9\\d{2})\\d{3}([- ])(?!00)\\d{2}\\1(?!0{4})(\\d{4})";
    testSSNRegex(pStr);
  }
  
  @Test
  public void regexBackNamedGroupReference() {
    String pStr = "(?!219-09-9999|078-05-1120)(?!666|000|9\\d{2})\\d{3}(?<SEP>[- ])(?!00)\\d{2}\\k<SEP>(?!0{4})(\\d{4})";
    testSSNRegex(pStr);
  }
  
  public void testSSNRegex(String pStr) {
    Matcher m = Pattern.compile(pStr).matcher("123 45 6789");
    if (m.matches()) {
      System.out.println(m.group());
    } else {
      fail("Didn't find match");
    }
    m = Pattern.compile(pStr).matcher("123-45-6789");
    if (m.matches()) {
      System.out.println(m.group());
    } else {
      fail("Didn't find match");
    }
    
    m = Pattern.compile(pStr).matcher("123-456789");
    if (m.matches()) {
      fail("Should not find match");
    }
  }
References
Validating Social Security Numbers through Regular Expressions
Named Capturing Group in JDK7 RegEx

Regular Expression in Action: Remove or Merge Empty Lines


The Problem
I like to copy the code to Eclipse or NetBeans to read it and run it when read some interesting code in internet. The code in the web is usually not well formatted: many empty lines. This makes it harder to read the code.
So I like to remove empty lines  to make the code looks smaller and concise.

Here regex comes into play.

Remove Empty Lines

Find: ^\s*\n
Replace: (empty)

Merging Empty Lines
Find: ^\s*\n
Replace: \r\n or \n in windows 

Next, use Ctrl+Shif+F in Eclipse or Alt+Shif+F in Netbeans to fromat the code.

Online Regex Tools
http://regex101.com/
Here it will explain the meaning of the regular expression, we can test it.
  • /^\s*\n/
    • ^ assert position at start of the string
    • \s* match any white space character [\r\n\t\f ]
      • Quantifier: Between zero and unlimited times, as many times as possible, giving back as needed [greedy]
    • \n matches a fine-feed (newline) character (ASCII 10)
http://www.regexplanet.com/
Here we can test our regualr expression in almost all languages, it can also give its java or .Net String, so we don't have to manually escape special chracters such as \ or " in the regex string.

Debugging and Optimizing Regular Expression


In last post, Using HTML Parser Jsoup and Regular Expression to Extract Text between Tow Tags, I introduced how to use Jsoup and Regular Expression to extract content between two anchor tags. 

Current regex is: 
<span[^>]*\bid\s*=\s*(?:"|')?JDK_contents(?:'|")?[^>]*>([^<]*)</span>(.*?)<span[^>]*\bid\s*=\s*(?:"|')?Ambiguity_between_a_JDK_and_an_SDK(?:'|")?[^>]*>[^<]*</span>.*
Writing efficient Regex is complicated, luckily there are several tools that can help us.

The best one is RegexBuddy. The trail RegexBuddyCookbook.exe is fully functional for seven days of actual use. 

Select Regex language(Java, Python, etc), type regex string, paste content in test panel, then click "Debug till end" from Debug drop-dwon buttons. In the debug panel, it will list all steps the regex engine executes.

In the Create panel, RegexBuddy will give the explanation of the regex. Select one token then click "Explain Token". We can also export the regex string and the explanation.
In the convert panel, we can convert between different regex languages.

Other Tools
regexplanet
We can use regexplanet to covert regex string to a java string. 

Regex Optimization Tips
Use the any (dot) operator sparingly.
Use the non-capturing group (?:pattern) if possible.
Use the atomic group (or non-backtracking subexpression) when applicable (?>pattern).
Alternation: The order of alternation counts, so place the more common options in the front so they can be matched faster.

Resources
Optimizing regular expressions in Java
regexplanet
regexbuddy

Removing Invalid Control Characters from XML


The Problem
Today, our application reports following error when import one xml data to Solr:
<str name="msg">Illegal character ((CTRL-CHAR, code 22)) at [row,col {unknown-source}]: [1,115]</str>

Via Eclipse remote debug, I got the xml data client sent:
<field name="lnks">\MB\abc def....</field>
It's obvious that this is because of the invalid Control Character "synchronous idle" character in the XML data.

Putting the field value in  CDATA tag won't help in this case, as from http://msdn.microsoft.com/en-us/library/ms256076.aspx:
Content within CDATA sections must be within the range of characters permitted for XML content; control characters and compatibility characters cannot be escaped this way. In addition, the sequence ]]> cannot appear within a CDATA section because this sequence signals the end of the section. This means that CDATA sections cannot be nested. The sequence also appears in some scripts. Within scripts, it is usually possible to substitute] ]> for ]]>.

The Fix
To fix this, we have to remove these special control characters from xml data or replace them with other character like space or dash.
We can do this easily at client side: just write a function to replace or remove these special control characters or reuse existing library, such as Guva
CharMatcher.JAVA_ISO_CONTROL.removeFrom(string);
str = str.replaceAll("\\p{Cntrl}", "");
or str = str.replaceAll("[\\p{Cntrl}^\r\n\t]+", "");

Explanation

CharMatcher.JAVA_ISO_CONTROL characters are in range '\u0000' - '\u001F' and '\u007F' - '\u009F'. They are invisible and invlaid in XML, and have no meaning in text processing.

Determines if the referenced character (Unicode code point) is an ISO control character. A character is considered to be an ISO control character if its code is in the range '\u0000' through '\u001F' or in the range '\u007F' through '\u009F'.

The code point U+0000, assigned to the null control character, is the only character encoded in Unicode and ISO/IEC 10646 that is always invalid in any XML 1.0 and 1.1 document.
U+0001–U+0008, U+000B–U+000C, U+000E–U+001F : this includes most (not all) C0 control characters
U+007F–U+0084, U+0086–U+009F  : this includes a C0 control character, and all but one C1 control

Resources
http://msdn.microsoft.com/en-us/library/ms256076.aspx
http://stackoverflow.com/questions/14028716/how-to-remove-control-characters-from-java-string
http://unicode-table.com/en/

Labels

ANT (6) Algorithm (69) Algorithm Series (35) Android (7) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) JSON (7) Java (186) JavaScript (27) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) adsense (5) bat (8) regex (5) xml (5)