Pattern matching a string

I'm trying to pattern match a string in java which has the following syntax:
ENSMUS followed by one character which can be anything followed by 11 digits.
I've done this in javascript using the following regex:
var regex = /^ENSMUS(\w{1})(\d{11})$/;I'm slightly confused by the Java equivalent (having looked at the Pattern class in the API). Could anyone lend a hand please?

ENSMUS followed by one character which can be
anything followed by 11 digits.
String s = ...
boolean b = s.matches("ENSMUS.\\d{11}");Note that when matching an entire String, you don't
need to provide a beginning (^) and end ($) in your
regex. Also, you said "any character", this is not
\w, but a . (a period). \w is a "word character".So I assume if it was a word character it would be
String s = ...
boolean b = s.matches("ENSMUS\\w{1}\\d{11}");I'll try it and see what happens. Thanks

Similar Messages

  • Pattern matching in String

    Hi,
    I want to do pattern matching using String. Here is my requirement.
    String file_name = (String)hash.get("DOCNAME"));
    file_name = file_name.replace("'","285745@");
    So, whereever I have '(apostrophe) I will replace it with pattern "285745@" and then at another jsp where I get this request parameter I do reverse as follows:
    String docname = (String)request.getParameter("doc_name").replace("285745@","'");
    Now I know replace function is not going to do this. It is just a indicative, for you to know what I want to achieve. which other java function / method i can implement to get the desired result.
    thanks,
    pp

    String file_name = (String)hash.get("DOCNAME"));
    file_name = file_name.replace("'","285745@");The problem here is that String.replace() operates only on char arguments, you cannot replace entire substrings with it.
    The String.replaceAll() method, on the other hand, operates on regular expressions. In many common cases (those in which the substring you want to find contains no characters with special meaning to the regular expression processor) you can use it exactly as you would String.replace() except that it operates on substrings.
    But regular expressions are much more powerful than that. The javadoc for the "Pattern" class has some information on how to use them. There is also a tutorial at http://java.sun.com/docs/books/tutorial/extra/regex/intro.html which you might find helpful.
    In the 1.4 edition of Java there is no longer any need to screw around with while loops and StringBuffers. Nearly any text processing operation can be done with regular expressions.

  • Pattern matching in Strings

    Hi,
    I need some help using pattern matching in strings .. this is what i need to do ..
    if given a string of this format
    String tempNotes="07/07/05 3:42 PM - 65. Java forum test 07/01/05 5:11 PM - 62. Trying regualt Expressions";I need to extract the number(s) after the time .. in the above case would be 65,62 .
    The string might have more than one line of the above format .. can some one help me with this .
    I tried using regular expressions .. I am pretty new to Regex's tried this
    String regex="\\d(2)/\\d(2)/\\d(2)\\s\\d+:\\d(2)\\sP|AM\\s-";
    Pattern p= Pattern.compile(regex);
    Matcher m1 = p.matcher(tempNotes);
    if(m1.find()){
    System.out.println("Num = "+tempNotes.substring(m1.end()+1,m1.end()+3));
    } I am totally lost .. can someone help me with this please. I need to extract all the numbers after the time .
    Thanks in advance.

    I see two major problems with that regex. First, you're using parentheses where you should be using braces - "\\d{2}", not "\\d(2)". Second, you need to need to limit the scope of the alternation: "(?:P|A)M", or better, use a character class instead: "[PA]M". As it is, the vbar is splitting the whole regex into two alternatives. Also, you can use a capturing group to extract the number.
      String regex="\\d{2}/\\d{2}/\\d{2}\\s\\d+:\\d{2}\\s[AP]M\\s-\\s+(\\d+)";
      Pattern p= Pattern.compile(regex);
      Matcher m1 = p.matcher(tempNotes);
      while (m1.find()) {
        System.out.println("Num = " + m1.group(1));
      }

  • Pattern matching String

    Hi,
    I want to do pattern matching using String. Here is my requirement.
    String file_name = (String)hash.get("DOCNAME"));
    file_name = file_name.replace("'","285745@");
    So, whereever I have '(apostrophe) I will replace it with pattern "285745@" and then at another jsp where I get this request parameter I do reverse as follows:
    String docname = (String)request.getParameter("doc_name").replace("285745@","'");
    Now I know replace function is not going to do this. It is just a indicative, for you to know what I want to achieve. which other java function / method i can implement to get the desired result.
    thanks,
    sa pa

    Hi,
    I want to do pattern matching using String. Here is my requirement.
    String file_name = (String)hash.get("DOCNAME"));
    file_name = file_name.replace("'","285745@");
    So, whereever I have '(apostrophe) I will replace it with pattern "285745@" and then at another jsp where I get this request parameter I do reverse as follows:
    String docname = (String)request.getParameter("doc_name").replace("285745@","'");
    Now I know replace function is not going to do this. It is just a indicative, for you to know what I want to achieve. which other java function / method i can implement to get the desired result.
    thanks,
    sa pa

  • Regular expression and pattern matching/replacing

    I have a list of key words. It has around 1000 key word now but can grow to 5000 keywords.
    My web application displays lot of texts which are stored in the database. My requirement is to scan each text for the occurance of any of the above keywords. If any keyword is present I have to replace that with some custom values, before showing it to the user.
    I was thinking of using using regular expression for replacing the keyword in the text using matcher.replaceAll method as follows:
    Pattern pattern = Pattern.compile(patternStr);
    Matcher matcher = pattern.matcher(inputStr);
    String output = matcher.replaceAll(replacementStr);
    But My pattern string will have around 5000 keywords with the 'OR' Logical Operator like- keyword1| keyword2 I keyword3 | ..........
    Will such a big pattern string adversly affect the performance? What can I do to speed up the performance? (Since my keyword list is not static i would prefer to do the replacement just before showing the text to the user)
    Any suggestions are most welcome.

    I don't think a pure regex approach would be that slow, but it would be a maintenance nightmare. I think a combined regex/table-lookup approach would be best: use a regex to identify potential keywords, then look them up in the table to confirm. For instance, to find all Java keywords you could use the regex "\\b[a-z]{2,12}+\\b" to filter out anything that can't possibility be a keyword.
    What are you going to replace the keywords with? Will it vary depending on which keyword is found? If so, you'll have to use a table--and you won't be able to use the replaceAll method, because it can't handle dynamically generated replacement values. You would have to use the lower-level appendReplacement and appendTail method instead.

  • Latin 1 supplement for Pattern matching

    Hi All,
    I am trying to pattern match a string with the following pattern:
    "\\p{InLatin1Supplement}+"(want to allow only characters in Latin 1 Supplement charset)
    However I get java.util.regex.PatternSyntaxException: Unknown character family {Latin1Supplement}Please suggest what should be the proper string for the pattern.
    Thank you !!

    Hm, have your checked Blocks-3.txt, as it says in the javadocs?
    "Unicode blocks and categories are written with the \p and \P constructs as in Perl. \p{prop} matches if the input has the property prop, while \P{prop} does not match if the input has that property. Blocks are specified with the prefix In, as in InMongolian. Categories may be specified with the optional prefix Is: Both \p{L} and \p{IsL} denote the category of Unicode letters. Blocks and categories can be used both inside and outside of a character class.
    The supported blocks and categories are those of The Unicode Standard, Version 3.0. The block names are those defined in Chapter 14 and in the file Blocks-3.txt of the Unicode Character Database except that the spaces are removed; "Basic Latin", for example, becomes "BasicLatin". The category names are those defined in table 4-5 of the Standard (p. 88), both normative and informative."
    Other than that, I don't know, sorry.

  • A regular expressin problem: String.matches & the pair of Pattern & Matcher

    I observe this problem when working on pattern match for Z5Z-5Z5, Z5Z 5Z5 or Z5Z5Z5.
    When I use the match method of the String class, the correct pattern will yield true with
    !str.matches("^[A-Za-z]\\d[A-Za-z]\\s?|-?\\d[A-Za-z]\\d$").
    When I use the pair classes of regex:
    Pattern p = Pattern.compile("^[A-Za-z]\\d[A-Za-z]\\s?|-?\\d[A-Za-z]\\d$");
    Matcher m = p.matcher(str);
    a string of "v7u h4e" (two blank spaces in between) can pass the !m.find().
    Have anyone else experienced the same situation?
    Do I use them right, or bugs?
    Thanks for your input.
    v.

    This is why I wish regex references would list the
    operator precedence. What do you mean? My regex reference does show that right under the section called "Operators" in the second chapter.
    Maybe you need to update your references and buy "Programming Perl"? :)
    I think there are only three
    levels of precedence, but it needs to be crystal clear
    that | has the lowest precedence (even lower than
    putting two tokens together!) and often needs
    parentheses: "\w\d|\s\w" means "(\w\d)|(\s\w)", not
    "\w(\d|\s)\w".Actually for that particular operator it is pretty consistent. It is always very low. Even when I was introduced to the theory of regex's in school the precedence was lower than everything else.

  • Match pattern for multiple strings in labVIEW

    I want to include multiple strings for matching in the regular expression for pattern matching.I tried using the or option and (|)
    eg:cat|dog|mouse
    If the string contains any of these it should show a match.
    Is it possible in labview or do i need to use multiple patch mattern functions to achieve this?

    Match Regular Expression function will do.
    You can search for multiple strings using | operator. This function will return the match of any one of the specified strings seperated by | operator

  • How to search for a particular pattern in a string

    Hi,

    Hi ,
    How to search for a particular pattern in a string?
    I heard about java.util.regex; and used it in my jsp program.
    Program I used:
    <% page import="java.util.regex"%>
    <% boolean b=Pattern.matches("hello world","hello");
    out.println(b);%>
    I run this program using netbeans and am getting the following error message.
    "Cannot find the symbol : class regex"
    "Cannot find the symbol : variable Pattern "
    How to correct the error?

  • Regular Expressions (Pattern/Matcher) --- Help

    Hi,
    I have an regex i.e. Pattern.compile("([0-9])D([0-9])'?(?:([0-9]+)\")?([NSEW])").{code}
    It has to exactly match the input e.g *45D15'34"N*
    I need to retrieve the values based on grouping.
    Group1 = 45 (degree value)
    Group2 = 15 (minutes value)
    Group3 = 34 (seconds value) ----> this is a non-capturing group
    Group4 = N (directions)
    The regex works fine for most of longitude/latitude value but I get a StackOverFlow for some. There is a known bug on this http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=5050507
    According to the bug report, they have said that are many different regex that can trigger the stack overflow....even though the length of my input is not as long as the one posted on the bug report.
    I was wondering if anyone could suggest a different way of writing the regex above to avoid the stack over flow.
    Thank you in advance                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               

    Hi,
    I missed the '+' in my original regex Pattern.compile("([0-9]+)D([0-9]+)'?(?:([0-9]+)\")?([NSEW])"){code}.
    I have also tried {code} Pattern.compile("(\\d+)D(\\d+)'?(?:(\\d+)\")?([NSEW])");And, the other 2 expressions as suggested by you.
    The problem happens when Durham Lat=”35D52’N” Lon=”78D47’W value is selected from a Jtree(the values are parsed from a xml file to the tree - the xml file has a bout 800 longitude/latitude elements for different cities in the US). It does not happen for other values and If I increment the degree or min by, then the expression works. I am not sure how else i could re-write this exp.
    Below is the snippet of the xml file:
    <State name="NORTH CAROLINA">
                <City name="Asheville AP"     Lat="35D26'N"     Lon="82D32'W"/>
                <City name="Charlotte AP"     Lat="35D13'N"     Lon="80D56'W"/>
                <City name="Durham"     Lat="35D52'N"     Lon="78D47'W"/>
                <City name="Elizabeth City AP"     Lat="36D16'N"     Lon="76D11'W"/>
                <City name="Fayetteville, Pope AFB" Lat="35D10'N"     Lon="79D01'W"/>
                <City name="Goldsboro,Seymour-Johnson"     Lat="35D20'N"     Lon="77D58'W"/>
                <City name="Greensboro AP (S)"     Lat="36D05'N"     Lon="79D57'W"/>
                <City name="Greenville"     Lat="35D37'N"     Lon="77D25'W"/>
                <City name="Henderson"     Lat="36D22'N"     Lon="78D25'W"/>
                <City name="Hickory"     Lat="35D45'N"     Lon="81D23'W"/>
                <City name="Jacksonville"     Lat="34D50'N"     Lon="77D37'W"/>
                <City name="Lumberton"     Lat="34D37'N"     Lon="79D04'W"/>
                <City name="New Bern AP"     Lat="35D05'N"     Lon="77D03'W"/>
                <City name="Raleigh/Durham AP (S)"     Lat="35D52'N"     Lon="78D47'W"/>
                <City name="Rocky Mount"     Lat="35D58'N"     Lon="77D48'W"/>
                <City name="Wilmington AP"     Lat="34D16'N"     Lon="77D55'W"/>
                <City name="Winston-Salem AP"     Lat="36D08'N"     Lon="80D13'W"/>
            </State>
    public final class GeoLine {
        /* Enum for the possible directions of longitude and latitude*/
        public enum Direction {
            N, S, E, W;
            public boolean isLongitude() {
                return (this == E || this == W);
            public boolean isLatitude() {
                return (this == N || this == S);
            public Direction getCanonicalDirection() {
                if (this == S) {
                    return Direction.N;
                } else if (this == W) {
                    return Direction.E;
                } else {
                    return this;
        private final int degree;
        private final int minute;
        private final int second;
        private final Direction dir;
        /* Recognizes longitude and latitude values that has degrees, minutes and seconds i.e. "45D15'34"N
        * or "45D1534"N. The single-quotes for the minutes is optional. And, for the moment we do not support seconds
        * validation although ilog library returns the longitude/latitude with second when NEs and Sub-networks are
        * dragged and dropped on the map.*/
    private static final Pattern PATTERN = Pattern.compile("([0-9]+)D([0-9]+)'?(?:([0-9]+)\")?([NSEW])");
        public GeoLine(int degree, int minute, Direction dir) {
            this(degree, minute, 0, dir);
        public GeoLine(int degree, int minute, int second, Direction dir) {
            Log.logInfo(getClass().getSimpleName(), "PAU degree: " + degree + " minute: " + minute + " second: " + second + " direction: " +  dir);
            verifyLongitudeLatitude(degree, dir);
            verifyMinute(degree, minute, dir);   
            this.degree = degree;
            this.minute = minute;
            this.second = second;
            if (this.degree == 0 && this.minute == 0 && this.second == 0) {
                this.dir = dir.getCanonicalDirection();
            } else {
                this.dir = dir;
        public Direction getDirection() {
            return dir;
        public int getMinute() {
            return minute;
        public int getDegree() {
            return degree;
        public int getSecond() {
            return second;
        public static GeoLine parseLine(String location) {
            * Matcher class will throw java.lang.NullPointerException if a null location
            *  is passed, null location validation is not needed.
            Matcher m = PATTERN.matcher(location);
            if(m.matches()) {
                int deg;
                int min;
                int second;
                Direction direction;
                deg = Integer.parseInt(m.group(1));
                min = Integer.parseInt(m.group(2));
                if (m.group(3) == null) {
                    second = 0;
                } else {
                    second = Integer.parseInt(m.group(3));
                direction = Direction.valueOf(m.group(4));
                return new GeoLine(deg, min, second, direction);
            } else {
                throw new IllegalArgumentException("Invalid location value. Expected format XXDXX'XX\"[NSEW] " + location);
        private void verifyMinute(int deg, int min, Direction direction) {
            /* This validation is to make sure that minute does not exceed 0 if maximum value for latitude == 90
            * or longitude == 180 is specified */
            int maxDeg = direction.isLatitude() ? 90 : 180;
            if(min < 0 || min > 59) {
               throw new NumberFormatException("Minutes is out of range. Value should be less than 60: " + min);
            if (deg == maxDeg && min > 0) {
                throw new NumberFormatException("Degree value " + deg + "D" + direction + " cannot have minute exceeding 0: " + min);
        private void verifyLongitudeLatitude(int valDeg, Direction valDir) {
               int max = valDir.isLatitude() ? 90 : 180;
               if(valDeg < 0 || valDeg > max) {
                    throw new NumberFormatException("Degree " + valDeg + valDir + " is invalid");
        public final boolean isLongitude() {
            return dir.isLongitude();
        public final boolean isLatitude() {
            return dir.isLatitude();
        @Override
        public final String toString(){
            if(minute < 10){
                return degree + "D0" + minute + dir;
            } else {
                return degree + "D" + minute + dir;
        @Override
        public boolean equals(Object obj) {
            if (obj instanceof GeoLine) {
                GeoLine other = (GeoLine) obj;          
                    return (this.degree == other.degree && this.minute == other.minute && this.second == other.second && this.dir == other.dir);
            return false;
        @Override
        public int hashCode() {
            int result = 17;
            result = result * 37 + degree;
            result = result * 37 + minute;
            result = result * 37 + second;
            result = result * 37 + dir.hashCode();
            return result;
    }Thank you again.

  • Who knows how to output some text once labview detects something I want using pattern matching(V​ision assistant)​?

    who knows how to output some text once labview detects something I want using pattern matching(Vision assistant)?
    The text is something like"Yes, this is a coin"
    Thanks!

    I attached a SubVI which I used to place an overlay next to a Pattern, found by a Pattern Match before:
    As you can see, you simply pass the image reference and the Array of Matches to the VI along with the String you want to have as an overlay next to the Match.
    I also modified your VI a bit, but didn't test it. I created an Array of clusters, each elment containing the template path along with the respective text.
    Please note that this is just a hint!
    Christian
    Attachments:
    suggestion.vi ‏146 KB
    Overlay_Txt.vi ‏24 KB

  • Pattern matching problme - not getting desired result.

    Hi,
    According my program , If 'san' is in 'sangeetha', then it should display "hello".
    but I am getting only 'hi'
    Why ? any idea?
    <%@ page import="java.util.regex.Pattern"%>
    <%
    if(Pattern.matches("san", "sangeetha"))
    out.println("hello");
    else
    out.println("hi");
    %>
    Result : Hi

    sangee wrote:
    Hi,
    According my program , If 'san' is in 'sangeetha', then it should display "hello".No, that isn't what your patten say. You should read about regular expressions and learn how to use them, or switch to String.indexOf or contains.
    Kaj

  • Pattern matching for range of numbers

    I am facing problem in using a pattern like [200-300] to match any number in the range 200 and 300 inclusive. I wrote following code:
    public class RangeTest {
         public static void main(String[] args) {
              String pat = "[100-200]";
              String input = "100";
              // incpat.replace("[", "\\[");
              // incpat.replace("]", "\\]");                    
              System.out.println("Pattern" + pat);
              Pattern pattern = Pattern.compile(pat);
              Matcher matcher = pattern.matcher(input);
              if (matcher.matches()) {
                   System.out.println("EPC Matched:" + input + " and pattern:"              +matcher.pattern());                         
    }and tested it for different values of input , it's not working. I tried even giving escape characters for "[" and "]" (commented code). Can i use pattern matching in this case.
    Please help me.
    Regards,
    Prashanth

    I am facing problem in using a pattern like[200-300] to match any number in
    the range 200 and 300 inclusive.Try this one: "(2\d\d)|(300)".
    kind regards,
    Jos
    ps. Waiting for Sabre to jump in telling me that the
    parentheses aren't needed ;-)The parentheses aren't needed Jos! :-)

  • Pattern Matching problems

    Hi people,
    I'm having a slight problem with pattern matching. What I need to do is find if my pattern is a given string an return the end index.
    Here's my string:
    <TD>Some text</TD>
    I need to find everything between the 2 anchor tags. (In this case "Some text"). The query string parameters are the only thing that can change.
    Here's what I've tried:
    Pattern pattern = Pattern.compile("<a href=\"/cgi-bin/dir/program.cgi?PARAM1=[0-9]&PARAM2=[0-9]*\"onmouseover=\"window.status='';return true;\">");
    Matcher matcher = pattern.matcher(myString);
    if ( matcher.find() ) {
       System.out.println(matcher.end());
       System.out.println(myString.substring(matcher.end(), myString.toLowerCase().indexOf("</a>",matcher.end())));               
    }Of course I've tried a lot of other things. I've also googled to try to find some examples but to no avail.
    Thanks for any help.

    Just change your Patterne. It will work. The '?' character is being considered as a pattern matching character, while you want it as it is. Use \\ before '?' character.
    Pattern pattern = Pattern.compile("<a href=\"/cgi-bin/dir/program.cgi\\?PARAM1=[0-9]&PARAM2=[0-9]*\"onmouseover=\"window.status='';return true;\">");
    Hope it helps.

  • Pattern / matcher question

    Hi,
    I have this arrayList<String>
    arr = { "minor", "division", "substraction","maximum","minimum" }
    and I want to scan this file with these patterns:
    file.txt
    $inor %ubstracti*&
    $ini$u$ (ivisi*&
    $axi$u$ %ubstracti*&
    correcting this files. Additionaly I want to "remember" which sign was corrected (for example in here we have "$ = M"). I'll need this to
    swap all signs in whole file. If I'll discover that $ i a M sign then I would like to change all $ to M. This should help me to encode this file.
    Any ideas?

    nordvik_ wrote:
    I have this arrayList<String>
    arr = { "minor", "division", "substraction","maximum","minimum" }
    and I want to scan this file with these patterns:
    file.txt
    $inor %ubstracti*&
    $ini$u$ (ivisi*&
    $axi$u$ %ubstracti*&
    correcting this files. Additionaly I want to "remember" which sign was corrected (for example in here we have "$ = M"). I'll need this to
    swap all signs in whole file. If I'll discover that $ i a M sign then I would like to change all $ to M. This should help me to encode this file.
    Any ideas?I think you need to clarify the rules a bit more:
    1. Is this file made up of blank-delimited words?
    2. Are you only ever going to be matching words, or do you need to match any string in the file?
    3. Are the words in your 'arr' array guaranteed to be unambiguous, or could you match more than one of them in the file?
    4. If the answer to 3 is 'no' (ie, words could be ambiguous) is the totality of 'arr' guaranteed to be unambiguous (ie, is there only one solution that will satisfy all the words)?
    Winston

Maybe you are looking for

  • Keeps reading out emails and sms

    Hi My phone noe reads out emails received ans SMS. It is only on the email application and not gmail I have reset application preferences Subsequently I have unticked email notifications in the email account setting and unticked notifications in the

  • My Spry Horizontal Menu doesn't work

    I created my Spry horizontal menu and tried it in preview browser and it doesn't work.  I published the site to see if it check didn't work in preview mode and it REALLY doesn't work. I'm sure it's something simple that I am just missing, but what I

  • Prime Infrastructure 2.0 no 'Add a WLAN' option

    Hello, I've started to pay with PI 2.0 and I've noticed that there is no option to add new WLAN. I am following manual: Step 1 Choose Configure > Controllers. Step 2 Click the IP address of the appropriate controller. Step 3 From the left sidebar men

  • Telemetry & Zone Clusters

    Does anyone know a good source for configuring cluster telemetry, specifically with zone clusters? I can't find much in the cluster documentation or by searching oracle's website. The sctelemetry man page wasn't very useful. The sun cluster essential

  • Satellite L500D - Missing drivers for Windows XP

    I apologize for my English, I am a Pole:) Hi I have a big problem, (I installed XP SP3 on L500D-149 PSLT0E) and now most importantly, I can not find drivers for: - System management bus controller - Video controller (ATI Radeon HD 3200) Not approache