Regular expressions: Difference between revisions

From Rosetta Code
Content added Content deleted
m (first java example)
m (→‎[[Java]]: substitute)
Line 16: Line 16:
}
}


Substitute

String orig = "I am the original string";
Pattern pat = Pattern.compile("original"); // match "original"
Matcher mat = pat.matcher(orig); // get the Matcher

String result = mat.replaceAll("modified"); // replace all matches against the pattern with "modified"
// result is now "I am the modified string"


==[[Perl]]==
==[[Perl]]==

Revision as of 20:11, 24 January 2007

Task
Regular expressions
You are encouraged to solve this task according to the task description, using any language you may know.

The goal of this task is

  • to match a string against a regular expression
  • to substitute part of a string using a regular expression

Java

Java info: java version "1.5.0_06", Java(TM) 2 Runtime Environment, Standard Edition (build 1.5.0_06-b05), Java HotSpot(TM) Client VM (build 1.5.0_06-b05, mixed mode, sharing)

Test

String str = "I am a string";
if (str.matches(".*string$")) {
  System.out.println("ends with 'string'");
}

Substitute

String orig = "I am the original string";
Pattern pat = Pattern.compile("original"); // match "original"
Matcher mat = pat.matcher(orig); // get the Matcher
String result = mat.replaceAll("modified"); // replace all matches against the pattern with "modified"
// result is now "I am the modified string"

Perl

Interpreter: Perl v5.8.8

Test

$string = "I am a string";
if ($string =~ /string$/) {
  print "Ends with 'string'\n";
}

if ($string !~ /^You/) {
  print "Does not start with 'You'\n";
}

Substitute

$string = "I am a string";
$string =~ s/ a / another /; # makes "I am a string" into "I am another string"
print $string;

Test and Substitute

$string = "I am a string";
if ($string =~ s/\bam\b/was/) { # \b is a word border
  print "I was able to find and replace 'am' with 'was'\n";
}

Options

# add the following just after the last / for additional control
# g = globaly (match as many as possible)
# i = case-insensitive
# s = treat all of $string as a single line (incase you have line breaks in the content)
# m = multi-line (the expression is run on each line individually)
 
$string =~ s/i/u/ig; # would change "I am a string" into "u am a strung"