Sponsored Content
Top Forums Programming RegEx in Java. \b does not react to a newline Post 302421243 by durden_tyler on Friday 14th of May 2010 12:35:40 AM
Old 05-14-2010
Works fine for me:

Code:
$ 
$ 
$ # show the Java program
$ cat -n RegexTest.java
     1    import java.util.regex.Matcher;
     2    import java.util.regex.Pattern;
     3    public class RegexTest {
     4      public static void main(String[] args) {
     5        String str = "hello and bye\nand\nblah";
     6        String ptn = "\\b\\w+\\b";
     7        int num = 0;
     8        Pattern pattern = Pattern.compile(ptn);
     9        Matcher matcher = pattern.matcher(str);
    10        System.out.println("=======  String for inspection  =======");
    11        System.out.println(str);
    12        System.out.println("========================================");
    13        System.out.println("=======  Pattern to be searched  =======");
    14        System.out.println(ptn);
    15        System.out.println("========================================");
    16        boolean found = false;
    17        while (matcher.find()) {
    18          num++;
    19          System.out.println("Match # "+num+"\t:\t"+matcher.group()+"\t=>\tstarts at "
    20              + "index "+matcher.start()+" and ends at index "+matcher.end());
    21          found = true;
    22        }
    23        if (!found) {
    24          System.out.println("No match found");
    25        }
    26      }
    27    }
$ 
$ # compile
$ javac RegexTest.java
$ 
$ # run
$ java RegexTest
=======  String for inspection  =======
hello and bye
and
blah
========================================
=======  Pattern to be searched  =======
\b\w+\b
========================================
Match # 1    :    hello    =>    starts at index 0 and ends at index 5
Match # 2    :    and    =>    starts at index 6 and ends at index 9
Match # 3    :    bye    =>    starts at index 10 and ends at index 13
Match # 4    :    and    =>    starts at index 14 and ends at index 17
Match # 5    :    blah    =>    starts at index 18 and ends at index 22
$ 
$

tyler_durden
 

7 More Discussions You Might Find Interesting

1. Shell Programming and Scripting

Converting perl regex to sed regex

I am having trouble parsing rpm filenames in a shell script.. I found a snippet of perl code that will perform the task but I really don't have time to rewrite the entire script in perl. I cannot for the life of me convert this code into something sed-friendly: if ($rpm =~ /(*)-(*)-(*)\.(.*)/)... (1 Reply)
Discussion started by: suntzu
1 Replies

2. Shell Programming and Scripting

Modify or react on "cd" command

Hi folks, I found a pretty nice thread in this forum showing how to change the window title of a PuTTY window from within the shell. (Which I can't reference due having less than 5 postings?!?) I modified the solution a bit to have a function in my zshrc "wt()" changing the window title each... (8 Replies)
Discussion started by: mephistho
8 Replies

3. Shell Programming and Scripting

Add newline to regex

I have a perl script that runs a program and puts the output of the program into a variable. The output of the file looks like: Statistics 0 AverageTime: Statistics 0 AverageTime: I'm trying to run a regular express against this to pull out the first value in each of the parens... (1 Reply)
Discussion started by: Boomn4x4
1 Replies

4. Shell Programming and Scripting

Perl, RegEx - Help me to understand the regex!

I am not a big expert in regex and have just little understanding of that language. Could you help me to understand the regular Perl expression: ^(?!if\b|else\b|while\b|)(?:+?\s+){1,6}(+\s*)\(*\) *?(?:^*;?+){0,10}\{ ------ This is regex to select functions from a C/C++ source and defined in... (2 Replies)
Discussion started by: alex_5161
2 Replies

5. Shell Programming and Scripting

Sendmail K command regex: adding exclusion/negative lookahead to regex -a@MATCH

I'm trying to get some exclusions into our sendmail regular expression for the K command. The following configuration & regex works: LOCAL_CONFIG # Kcheckaddress regex -a@MATCH +<@+?\.++?\.(us|info|to|br|bid|cn|ru) LOCAL_RULESETS SLocal_check_mail # check address against various regex... (0 Replies)
Discussion started by: RobbieTheK
0 Replies

6. Web Development

Google Trends: react.js angular.js vue.js

While I'm on the subject of Google trends, here is a global trend since 2004 comparing react.js, angular.js, vue.js It's no secret I'm a vue.js fan and coder, but not because of the trend line (which I just saw for the first time a few minutes ago) My experience is that vue.js, a late arrival... (0 Replies)
Discussion started by: Neo
0 Replies

7. UNIX for Beginners Questions & Answers

Pass RegEx to java program in bash script

I can't seem to get this right. I've tried it every way imaginable using every trick I see on stackexchange and such. No luck. So nothing major here, something like: #!/bin/bash SEARCH="ARG1 ARG2 '((^EXACT$)|(.*InTheMiddle*)|(^AtBeginning*))'" java -cp /my/class/path MyClassName $SEARCH... (3 Replies)
Discussion started by: stonkers
3 Replies
guestfs-java(3) 					      Virtualization Support						   guestfs-java(3)

NAME
guestfs-java - How to use libguestfs from Java SYNOPSIS
import com.redhat.et.libguestfs.*; GuestFS g = new GuestFS (); g.add_drive_opts ("disk.img", null); g.launch (); DESCRIPTION
This manual page documents how to call libguestfs from the Java programming language. This page just documents the differences from the C API and gives some examples. If you are not familiar with using libguestfs, you also need to read guestfs(3). CLOSING THE HANDLE The handle is closed when it is reaped by the garbage collector. Because libguestfs handles include a lot of state, it is also possible to close (and hence free) them explicitly by calling the "close" method. EXCEPTIONS Errors from libguestfs functions are mapped into the "LibGuestFSException" exception. This has a single parameter which is the error message (a "String"). Calling any method on a closed handle raises the same exception. EXAMPLE 1: CREATE A DISK IMAGE // Example showing how to create a disk image. import java.io.*; import java.util.Map; import java.util.HashMap; import com.redhat.et.libguestfs.*; public class CreateDisk { static String output = "disk.img"; public static void main (String[] argv) { try { GuestFS g = new GuestFS (); // Create a raw-format sparse disk image, 512 MB in size. RandomAccessFile f = new RandomAccessFile (output, "rw"); f.setLength (512 * 1024 * 1024); f.close (); // Set the trace flag so that we can see each libguestfs call. g.set_trace (true); // Set the autosync flag so that the disk will be synchronized // automatically when the libguestfs handle is closed. g.set_autosync (true); // Attach the disk image to libguestfs. Map<String, Object> optargs = new HashMap<String, Object>() { { put ("format", "raw"); put ("readonly", Boolean.FALSE); } }; g.add_drive_opts (output, optargs); // Run the libguestfs back-end. g.launch (); // Get the list of devices. Because we only added one drive // above, we expect that this list should contain a single // element. String[] devices = g.list_devices (); if (devices.length != 1) throw new Error ("expected a single device from list-devices"); // Partition the disk as one single MBR partition. g.part_disk (devices[0], "mbr"); // Get the list of partitions. We expect a single element, which // is the partition we have just created. String[] partitions = g.list_partitions (); if (partitions.length != 1) throw new Error ("expected a single partition from list-partitions"); // Create a filesystem on the partition. g.mkfs ("ext4", partitions[0]); // Now mount the filesystem so that we can add files. g.mount_options ("", partitions[0], "/"); // Create some files and directories. g.touch ("/empty"); String message = "Hello, world "; g.write ("/hello", message.getBytes()); g.mkdir ("/foo"); // This one uploads the local file /etc/resolv.conf into // the disk image. g.upload ("/etc/resolv.conf", "/foo/resolv.conf"); // Because 'autosync' was set (above) we can just close the handle // and the disk contents will be synchronized. You can also do // this manually by calling g#umount_all and g#sync. // // Note also that handles are automatically closed if they are // reaped by the garbage collector. You only need to call close // if you want to close the handle right away. g.close (); } catch (Exception exn) { System.err.println (exn); System.exit (1); } } } EXAMPLE 2: INSPECT A VIRTUAL MACHINE DISK IMAGE // Example showing how to inspect a virtual machine disk. import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.List; import java.util.Map; import com.redhat.et.libguestfs.*; public class InspectVM { static final Comparator<String> COMPARE_KEYS_LEN = new Comparator<String>() { public int compare (String k1, String k2) { return k1.length() - k2.length(); } }; public static void main (String[] argv) { try { if (argv.length != 1) throw new Error ("usage: InspectVM disk.img"); String disk = argv[0]; GuestFS g = new GuestFS (); // Attach the disk image read-only to libguestfs. Map<String, Object> optargs = new HashMap<String, Object>() { { //put ("format", "raw"); put ("readonly", Boolean.TRUE); } }; g.add_drive_opts (disk, optargs); // Run the libguestfs back-end. g.launch (); // Ask libguestfs to inspect for operating systems. String roots[] = g.inspect_os (); if (roots.length == 0) throw new Error ("inspect_vm: no operating systems found"); for (String root : roots) { System.out.println ("Root device: " + root); // Print basic information about the operating system. System.out.println (" Product name: " + g.inspect_get_product_name (root)); System.out.println (" Version: " + g.inspect_get_major_version (root) + "." + g.inspect_get_minor_version (root)); System.out.println (" Type: " + g.inspect_get_type (root)); System.out.println (" Distro: " + g.inspect_get_distro (root)); // Mount up the disks, like guestfish -i. // // Sort keys by length, shortest first, so that we end up // mounting the filesystems in the correct order. Map<String,String> mps = g.inspect_get_mountpoints (root); List<String> mps_keys = new ArrayList (mps.keySet ()); Collections.sort (mps_keys, COMPARE_KEYS_LEN); for (String mp : mps_keys) { String dev = mps.get (mp); try { g.mount_ro (dev, mp); } catch (Exception exn) { System.err.println (exn + " (ignored)"); } } // If /etc/issue.net file exists, print up to 3 lines. String filename = "/etc/issue.net"; if (g.is_file (filename)) { System.out.println ("--- " + filename + " ---"); String[] lines = g.head_n (3, filename); for (String line : lines) System.out.println (line); } // Unmount everything. g.umount_all (); } } catch (Exception exn) { System.err.println (exn); System.exit (1); } } } SEE ALSO
guestfs(3), guestfs-examples(3), guestfs-erlang(3), guestfs-ocaml(3), guestfs-perl(3), guestfs-python(3), guestfs-recipes(1), guestfs-ruby(3), <http://libguestfs.org/>, <http://caml.inria.fr/>. AUTHORS
Richard W.M. Jones ("rjones at redhat dot com") COPYRIGHT
Copyright (C) 2011 Red Hat Inc. <http://libguestfs.org/> The examples in this manual page may be freely copied, modified and distributed without any restrictions. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA libguestfs-1.18.1 2013-12-07 guestfs-java(3)
All times are GMT -4. The time now is 08:41 AM.
Unix & Linux Forums Content Copyright 1993-2022. All Rights Reserved.
Privacy Policy