[ 
https://issues.apache.org/jira/browse/BEAM-7018?focusedWorklogId=281146&page=com.atlassian.jira.plugin.system.issuetabpanels:worklog-tabpanel#worklog-281146
 ]

ASF GitHub Bot logged work on BEAM-7018:
----------------------------------------

                Author: ASF GitHub Bot
            Created on: 23/Jul/19 16:59
            Start Date: 23/Jul/19 16:59
    Worklog Time Spent: 10m 
      Work Description: mszb commented on pull request #8859: [BEAM-7018] Added 
Regex transform for PythonSDK
URL: https://github.com/apache/beam/pull/8859#discussion_r306429138
 
 

 ##########
 File path: sdks/python/apache_beam/transforms/util.py
 ##########
 @@ -864,3 +867,223 @@ def add_window_info(element, 
timestamp=DoFn.TimestampParam,
 
     def expand(self, pcoll):
       return pcoll | ParDo(self.add_window_info)
+
+
+class Regex(object):
+  """
+  PTransform  to use Regular Expression to process the elements in a
+  PCollection.
+  """
+  @staticmethod
+  def _regex_compile(regex):
+    """Return re.compile if the regex has a string value"""
+    if isinstance(regex, str):
+      regex = re.compile(regex)
+    return regex
+
+  @staticmethod
+  @typehints.with_input_types(str)
+  @typehints.with_output_types(str)
+  @ptransform_fn
+  def matches(pcoll, regex, group=0):
+    """
+    Returns the matches if the element matched the Regex. Returns the
+    entire line (group 0 by default). Group can be integer value or a string
+    value.
+
+    Args:
+      regex: the regular expression string or (re.compile) pattern.
+      group: (optional) name/number of the group, it can be integer or a string
+        value.
+    """
+    regex = Regex._regex_compile(regex)
+
+    def _process(element):
+      m = regex.match(element)
+      if m:
+        yield m.group(group)
+    return pcoll | FlatMap(_process)
+
+  @staticmethod
+  @typehints.with_input_types(str)
+  @typehints.with_output_types(str)
+  @ptransform_fn
+  def all_matches(pcoll, regex):
+    """
+    Returns the matches if the entire line matches the Regex. Returns all
+    groups.
+
+    Args:
+      regex: the regular expression string or (re.compile) pattern.
+    """
+    regex = Regex._regex_compile(regex)
+
+    def _process(element):
+      m = regex.match(element)
+      results = list()
+
+      if m:
+        results.append(m.group())
+        for match in m.groups():
+          results.append(match)
+      if results:
+        yield results
+    return pcoll | FlatMap(_process)
+
+  @staticmethod
+  @typehints.with_input_types(str)
+  @typehints.with_output_types(typehints.KV[str, str])
+  @ptransform_fn
+  def matches_kv(pcoll, regex, keyGroup, valueGroup):
+    """
+    Returns the KV pairs if the string matches the regular expression, deriving
+    the key & value from the specified group of the regular expression.
+
+    Args:
+      regex: the regular expression string or (re.compile) pattern.
+      keyGroup: The Regex group to use as the key. Can be int or str.
+      valueGroup: The Regex group to use the value. Can be int or str.
+    """
+    regex = Regex._regex_compile(regex)
+
+    def _process(element):
+      match = regex.match(element)
+      if match:
+        yield (match.group(keyGroup), match.group(valueGroup))
+    return pcoll | FlatMap(_process)
+
+  @staticmethod
+  @typehints.with_input_types(str)
+  @typehints.with_output_types(str)
+  @ptransform_fn
+  def find(pcoll, regex, group=0):
+    """
+    Returns the matches if a portion of the line matches the Regex. Returns
+    the entire group (group 0 by default). Group can be integer value or a
+    string value.
+
+    Args:
+      regex: the regular expression string or (re.compile) pattern.
+      group: (optional) name of the group, it can be integer or a string value.
+    """
+    regex = Regex._regex_compile(regex)
+
+    def _process(element):
+      r = regex.search(element)
+      if r:
+        yield r.group(group)
+    return pcoll | FlatMap(_process)
+
+  @staticmethod
+  @typehints.with_input_types(str)
+  @typehints.with_output_types(str)
+  @ptransform_fn
+  def find_all(pcoll, regex):
+    """
+    Returns the matches if a portion of the line matches the Regex. Returns all
+    the groups as a List of string.
+
+    Args:
+      regex: the regular expression string or (re.compile) pattern.
+    """
+    regex = Regex._regex_compile(regex)
+
+    def _process(element):
+      m = regex.finditer(element)
+      results = list()
+      for match in m:
+        results.append(match.group())
+        for groupNum in range(0, len(match.groups())):
+          results.append(match.group(groupNum + 1))
+      if results:
+        yield results
+    return pcoll | FlatMap(_process)
+
+  @staticmethod
+  @typehints.with_input_types(str)
+  @typehints.with_output_types(typehints.KV[str, str])
+  @ptransform_fn
+  def find_kv(pcoll, regex, keyGroup, valueGroup):
+    """
+    Returns the matches if a portion of the line matches the Regex. Returns the
+    specified groups as the key and value pair.
+
+    Args:
+      regex: the regular expression string or (re.compile) pattern.
+      keyGroup: The Regex group to use as the key. Can be int or str.
+      valueGroup: The Regex group to use the value. Can be int or str.
+    """
+    regex = Regex._regex_compile(regex)
+
+    def _process(element):
+      matches = regex.finditer(element)
+      if matches:
+        for match in matches:
+          yield (match.group(keyGroup), match.group(valueGroup))
+
+    return pcoll | FlatMap(_process)
+
+  @staticmethod
+  @typehints.with_input_types(str)
+  @typehints.with_output_types(str)
+  @ptransform_fn
+  def replace_all(pcoll, regex, replacement):
+    """
+    Returns the matches if a portion of the line  matches the Regex and
+    replaces all matches with the replacement String.
+
+    Args:
+      regex: the regular expression string or (re.compile) pattern.
+      replacement: the string to be substituted for each match.
+    """
+    regex = Regex._regex_compile(regex)
+
+    def _process(element):
+      yield regex.sub(replacement, element)
+
+    return pcoll | FlatMap(_process)
+
+  @staticmethod
+  @typehints.with_input_types(str)
+  @typehints.with_output_types(str)
+  @ptransform_fn
+  def replace_first(pcoll, regex, replacement):
+    """
+    Returns the matches if a portion of the line matches the Regex and replaces
+    the first match with the replacement String.
+
+    Args:
+      regex: the regular expression string or (re.compile) pattern.
+      replacement: the string to be substituted for each match.
+    """
+    regex = Regex._regex_compile(regex)
+
+    def _process(element):
+      yield regex.sub(replacement, element, 1)
+
+    return pcoll | FlatMap(_process)
+
+  @staticmethod
+  @typehints.with_input_types(str)
+  @typehints.with_output_types(str)
+  @ptransform_fn
+  def split(pcoll, regex, outputEmpty=False):
+    """
+    Returns the list of string which was splitted on the basis of regular
+    expression and then outputs each item. It will not output empty items.
+
+    Args:
+      regex: the regular expression string or (re.compile) pattern.
+      outputEmpty: (optional) Should empty be output. True to output empties
+          and false if not.
+    """
+    regex = Regex._regex_compile(regex)
+    outputEmpty = bool(outputEmpty)
+
+    def _process(element):
+      r = regex.split(element)
+      if r and not outputEmpty:
+        r = list(filter(None, r))
+      yield r
 
 Review comment:
   Fix the type hints to `typehints.List[str]`. I think it's better to get 
results of each collection item rather then flattens them all. Your thoughts?
 
----------------------------------------------------------------
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.
 
For queries about this service, please contact Infrastructure at:
us...@infra.apache.org


Issue Time Tracking
-------------------

    Worklog Id:     (was: 281146)
    Time Spent: 9h  (was: 8h 50m)

> Regex transform for Python SDK
> ------------------------------
>
>                 Key: BEAM-7018
>                 URL: https://issues.apache.org/jira/browse/BEAM-7018
>             Project: Beam
>          Issue Type: New Feature
>          Components: sdk-py-core
>            Reporter: Rose Nguyen
>            Assignee: Shehzaad Nakhoda
>            Priority: Minor
>          Time Spent: 9h
>  Remaining Estimate: 0h
>
> PTransorms to use Regular Expressions to process elements in a PCollection
> It should offer the same API as its Java counterpart: 
> [https://github.com/apache/beam/blob/11a977b8b26eff2274d706541127c19dc93131a2/sdks/java/core/src/main/java/org/apache/beam/sdk/transforms/Regex.java]



--
This message was sent by Atlassian JIRA
(v7.6.14#76016)

Reply via email to