String.replaceAll () takes an argument of regex?

For the experienced:


It is not not to solve a problem to find work on hand made, but something for the discussion of other possibilities.

I have a file which must cut them before use. The file has several lines, and for each line of the format is ('X' is used to mark the beginning and the end of the line to show the invisible white space):
X12345678   9876543210 X
I need to replace the three spaces between two numeric characters with one and eliminate space of tailings. My code:
String line = null;
while ((line = inputStream.readLine()) != null) {
    Pattern pattern = Pattern.compile("\\s+");
    Matcher matcher = pattern.matcher(line);
    line = matcher.replaceAll(" ").trim();
    System.out.println("(" + line + ")");
Which works very well and produces the desired result:
(12345678 9876543210)
Would but not be simpler if replacement of the String class methods would do the same job? It is, say,
String line = null;
while ((line = inputStream.readLine()) != null) {
    line.replaceAll("\\d+", " ").trim();
    System.out.println("(" + line + ")");
I do this using JDeveloper 11.1.1.3, located in C:\Oracle\Middleware\jdeveloper\jdeveloper.exe and found out, C:\Oracle\Middleware\jdk160_18\jre\bin\client\jvm.dll is probably the JDK using the JDeveloper. I checked the API document online for Java version 6 to http://download.oracle.com/javase/6/docs/api/index.html, and it shows that the String class has these replacement methods that take the regex:
String replaceAll(String regex, String replacement) 
String replaceFirst(String regex, String replacement) 
But when coding, typing < font color = "green" > replace < / police > as a result of the variable string < font color = "green" > line < / police >, all the insight of Code appears include:
replace(Char, Char)                  String
replace(CharSequqnce, CharSequence)  String
replaceAll(String, String)           String
replaceFirst(String, String)         String
This seems to say that regex is not supported. If I do not take into account the suggestion of the foresight of Code and try anyway:
line.repaceAll("\\d+", " ");

or

line.replaceAll("  *", " ");
   // This second attempt uses the familiar regular expression in unix,
   // such as would be used in
   // $ echo $line | sed 's/  */ /g'
JDeveloper complain about this attempt. But it does not work either, simply echo back which entered into him.

What I want to do is play with it to find a way of writing acceptable regular expressions in the JDK in JDeveloper. What the API documentation has said is that regex is accepted and taken in charge, but his behavior, we know not if this is the case with the JDeveloper, or if it is supported, but the suggestion of the insight of Code isn't fair and my regular expressions are not correct.

All suggestions and insight would be much appreciated.


Newman

System.out.println ("1 2 3 4".replaceAll ("\\s {2},", "X")); is back "X 1 2 X 3 X 4"(p. ex. espaces consécutifs seulement sont obtenant remplacés). "»
I have not tested, but the \s character class may not include new lines. You can use \n If you want to include line breaks as well. Also, I used JDeveloper and jdk, I used is one that comes with Jdeveloper(e.g. \Oracle\Middleware\jdk160_21).

Edited by: Hyangelo may 9, 2011 11:03

Edited by: Hyangelo may 9, 2011 11:05

Tags: Java

Similar Questions

  • String replaceAll() help

        //kill characters method used to remove unwanted characters
        //from strings, takes in unedited string, returns formatted string
        private String killChars(String fixThis )
        {
            return fixThis.replaceAll("\\W", "");
        }//end
    Hey guys and girls.

    I have this method in one of my applications and I do not exactly get the results I want. Is there a way to manipulate the replaceAll function arguments so that it will replace all non alphanumeric except for spaces? In fact, I want to keep white space.

    Thank you

    Kyle

    I think you can use "[^ \\s\\w]", which is anything other than whitespace or Word because. try it, see if it does what it takes.

  • How to pass strings of path as arguments to applescript?

    Since InDesign Extend script, I have the code snippet:

    var docFolder = currentDoc.filePath.getRelativeURI("/"); "

    scriptPath var = (new File($.fileName).parent.getRelativeURI("/" "));

    var script = new file (scriptPath + "/ RunFileMaker.scpt");

    argArray var = new Array();

    argArray.push (docFolder);

    If {(script.exists)

    app.doScript (script, ScriptLanguage.applescriptLanguage, argArray);

    }


    My RunFileMaker.scpt applescript has been simplified to:


    on run {argv}

    Display alert point 1 argv

    end run


    I get the error message:

    < < script > > can make point 1 in string


    The bulk of the problem is I'm trying to pass a string path to the applescript.



    Hi Bill,

    Try this... ;-)

    on run
        display dialog item 1 of arguments
    end run
    
  • problem with String.replaceAll

    Everyone does not understand why "10,00".replaceAll (".") * ","0") == '00' and not '0'?"

    Looks like. * must match the whole string and replace it with '0 '.

    With the help of 1.6.0_17

    840419 wrote:
    Everyone does not understand why "10,00".replaceAll (".") * ","0") == '00' and not '0'?"

    Looks like. * must match the whole string and replace it with '0 '.

    He does.

        public static void main(String[] arg) {
            //System.out.println("10.00".replaceAll(".*", "0"));
            Pattern p = Pattern.compile(".*");
            Matcher m = p.matcher("10.00");
            while(m.find()) {
                // the first find() greedily matches everything
                // the second find() matches a 0(zero)-length charsequence at the end
                System.out.printf("[%s]\n",m.group());
            }
        }
    

    You want to

        public static void main(String[] arg) {
            //System.out.println("10.00".replaceAll(".+", "0"));
            Pattern p = Pattern.compile(".+");
            Matcher m = p.matcher("10.00");
            while(m.find()) {
                System.out.printf("[%s]\n",m.group());
            }
        }
    
  • interface not implemented

    I am really fedUp with code that promise to implement an interface

    but in fact is not, and yet always compiles!

    in the following code:

    ArrayList < String > words =...

    words.replaceAll (String::toUpperCase);

    Why line 2 compile sucssfuly?

    ArrayList.replaceAll takes a < E > UnaryOperator

    UnaryOperator < T > {}

    T apply (T, t);

    }

    While String.toUpperCase () implements the UnaryOperator < E > interface, String.toUpperCase () takes no arguments

    ==================================================================================

    in the following code from Oracle tutorials collections: aggregation operations:

    // a class to store total value and values count to get the average
    class Averager implements IntConsumer {
        int total = 0;
        int count = 0;
    
        public double average() {
            if(count > 0) return (double)total/count; else return 0;
        }
    
        public void accept(int newVal) {
            total += newVal;
            count++;
        }
    
        public void compine(Averager other) {
            total += other.total;
            count += other.count;
        }
    }
    
    // Code in the main class
    ArrayList<Integer> allVals = new ArrayList<Integer>();
    allVals.addAll(Arrays.asList(2, 3, 5, 7, 1, 89, 4, 5));
    
    Averager averageCollect =
        allVals.stream()
                 .collect(Averager::new, Averager::accept, Averager::compine);
    System.out.println(averageCollect.average());
    
    
    

    Why the code at line 25 compile sucssfuly?

    Averager.Accept and Averager.compine does not implement BiConsumer < T, U > Interface

    Interface BiConsumer < T, U > {}

    void accept (T, t, U u);

    }

    They both take a single argument?

    OK, let's look at in detail in the example

    List words = ... ;
    words.replaceAll(String::toUpperCase);
    

    As you noted, the replaceAll parameter is UnaryOperator, and String::toUpperCase does not implement this interface. So, how does this work?

    First, observe that String::toUpperCase is a reference of toUpperCase() method, which is an instance of string method. You can rewrite the reference method as follows, without changing the meaning:

    words.replaceAll((String s) -> s.toUpperCase());
    

    I stated the lambda parameter type just to make it clear that it's a chain, but it could just as easily be written as: s-> s.toUpperCase ().

    Observe that this lambda expression takes one parameter, a string, and returns a value, a string.

    Now let's look at List.replaceAll (). It take a UnaryOperatorparameter. It is an instance method, and the variable E is the type of the list parameter. Words being list, then words.replaceAll () will have a UnaryOperator as its parameter.

    Now let's look at UnaryOperator. This must be a functional interface, since we provide a lambda here. However, UnaryOperator himself is not all abstract methods. He inherited his unique abstract of its superinterface function method. If we look at thefunction, it has a single abstract method

    R apply(T t)
    

    which means that it takes a parameter of type T and returns a value of type R. Foregoing, we know we need a UnaryOperator, which extends thefunction, and the types of the abstract method will be

    String apply(String t)
    

    It is a method that takes a parameter, a string, and returns a value, a string. But look! That's exactly what the lambda expression

    (String s) -> s.toUpperCase()
    

    designated operational entities and the lambda expression is equivalent to

    String::toUpperCase
    

    It is so true that the String::toUpperCase, as a method, declare that it implements UnaryOperator. But we must look at the "forms" of the methods. String::toUpperCase is a reference to a method that takes a string is a parameter and returns a string. And UnaryOperator has one abstract method that takes a string as a parameter and returns a string. That's why String::toUpperCase works in a context where a UnaryOperator is necessary.

    A wrinkle here is that the toUpperCase() method is an instance method. It seems that it takes no arguments. However, as an instance method, it must be called on an object, the "receiver". The receiver is as a first argument implicit in a method; It's just that from a syntactic point of view, it occurs in a different place. Take the example of Averager:

    class Averager {
        void accept(Integer newVal) { ... }
        void combine(Averager other) { ... }
    }
    

    (I've changed around int to take into account the autoboxing).

    Here, accept() and combine() are instance methods, so they must be called on an instance of Averager. Which is like an additional implicit for each argument. Thus, accept() takes two arguments: an Averager and an integer and returns no value (empty). For example, Averager.accept () corresponds to BiConsumer, since his abstract method is accepted (Averager t, all over u).

    (Note that it is completely irrelevant that Averager.accept has the same method name as BiConsumer.accept).

    In addition, combine() takes two arguments, an Averager (receiver) and an another Averager (the parameter as 'other'). Similarly, combine() corresponds to BiConsumer.

  • Storage of functions with arguments as String

    I need to store a function with arguments in a string.

    Without arguments, you simply have to do sth. Like this:

    functionName:String = "Hello";

    This [FunctionName])

    Function Hello (): void {}

    "Hello, World";

    }

    But as soon as you enter arguments it becomes difficult.

    I came up with this:

    function getArgsFromFunction(_function: String): Array {}

    var argstart: int = _function.indexOf ("("); ")

    var argend: int = _function.indexOf ("") ");"

    var argstring: String = _function.substr (argstart + 1, argend - argstart - 1);

    var args: Array = argstring.split(",");

    Return args;

    }

    function getNameFromFunction(_function: String): String {}

    var nameEnd: int = _function.indexOf ("("); ")

    "stringname" var: String = _function.substr (0, nameEnd);

    return "stringname";

    }

    var f: String = "showMessage (A, B)";

    function showMessage(_args: Array): void {}

    trace (_args);

    }

    var _funct: function = this [getNameFromFunction (f)];

    _funct. Call (this, getArgsFromFunction (f));


    but it is not very flexible, very sturdy and seems unnecessarily complicated.

    Anyone know a faster way to achieve this?

    function parseF(s:String):void {}

    var a: Array = s.split ("("); ")

    var arg:Array = a [1].split(",");

    This [a [0]] (arg [0], arg [1] .substr (0, -1));

    }

  • IFmsNotifyAction: the long string arguments get corrupted

    I use addNotifyAction in an Auth plugin to trigger a function in the application AS code. As shown in the examples, I'm passing a variable FmsVariant to addParam to add a string value to the argument list. Apparently, if I pass a string more of 32 characters, there somewhere is corrupt. If I connect its value through "path" from the AS code, I often get randomly garbage, sometimes including part of the value of the original / part of the other strings that do not belong there. If I use a shorter string, everything works fine. I have reproduced the same problem using the original sample of AuthModule.cpp code, to which I've just added the following code (in MyFmsNotifyEvent::notify):

    Field of FmsVariant;
    If (m_pAev-> getField (IFmsAuthEvent::F_CLIENT_ID, field) is IFmsAuthEvent::S_SUCCESS)
    {
    IFmsNotifyAction * pAction = m_pAev-> addNotifyAction ("notified by adapter");
    pAction-> setClientId (field);
    field.setString ("myfunc");
    pAction-> setMethodName (field);
    field.setString("012345678901234567890123456789012"); 33 characters
    pAction-> addParam (field);
    }

    In the main.asc app, I just added:

    Client.prototype.myFunc (ARG) {trace (arg) ;}
  • split a string dynamically

    NodeList list2 = doc.getElementsByTagName("URL");
                    for (int i = 0; i < list2.getLength(); i++) {
                        Node textNode = list2.item(i).getFirstChild();
                        urllist.addElement(textNode.getNodeValue());
                    }
    

    I need to the parsed url value is separated in two.

    that the value is home/Video.aspx? videoID = 414 & CategoryID = 4

    I need the value after? "videoID = 414 & CategoryID = 4" to be stored in a separate string, I need to get it back

    can someone tell how to implement it.

    indexOf method takes the Argument od a character where the Splliting of the chain after mating.

    int j = a.indexOf ("place character here to Spllitted");

    you have the length totally in the integer b.

    If it is looks like Like.This

    String splittedString = a.substring (d, b);

  • Regex expression for <>media

    Hello

    I have data within the brackets <>
    and would need a regular expression to get the same correspondent.

    by example-data - < 111-1-111 > would just 111-1-111


    I tried to use the String.replaceall ("<","" "); featured, but can't figure out how to pass in the regular expression to check the closing ' > ' support.

    any suggestions on this would be very useful


    THX

    You are not one of those who wants to solve all the problems with a regex right? In the example you give simply stripping off the first and the last character (which can be done with a call unique substring()) already nets you what you want.

    In any case regex also works:

            String str = "<111-1-111>";
            String ret = str.replaceAll("[]", "");
            System.out.println("RET: " + ret);
    

    But without the T-I had to put this because otherwise I could not the forum to render the characters LT and GT: s

  • Cannot pass arguments to a Java exe file

    Hi, I need to execute a Java exe file. Exe works but I'm not able to provide a key to the exe parameter.

    String [] cmd = {"Dir1/the-file" exe"," "-param1", ' < ', ' text - file.txt ""};
    Process pr = rt.exec (cmd);

    He takes the first argument with no problems. But I can't take the ' < ' argument. Exe gives an error.
    In the windows command prompt, I need to clarify that the angular bracket as the other setting is
    the input to the exe file.

    Do I need to escape? or what is a solution to this problem?

    Thank you

    Published by: kooldba on February 12, 2012 14:25

    Published by: kooldba on February 12, 2012 14:26

    You must specify cmd.exe/c as the first two arguments, then everything you have now. ' < ' is not an argument of command-line in general, it is understood only by the shell.

  • User-defined function: BAD ARGUMENT TYPE, ERROR

    I am creating a function defined by the user, named DOTAN, to calculate the angle between two vectors X and Y.  The UDF looks like this: DEFINE (' DOTHAN (X, Y) = ACOS (DOT (X, Y) / (ABS (X) * ABS (Y)))')--> (see pic attached to the actual Calculator display).  The problem is that I can not set because as soon as I hit ENTER I get the warning: DEFINE ERROR: wrong Type of Argument.  I tested each component separately and I am sure that the problem is with the help of DOT (X, Y) inside a UDF, but I don't know why. Maybe I'm missing some setting related to the use of functions which take an argument that is greater than 1 inside a UDF. Just guessing. Any idea?

    Thank you

    for some reason, the DOWRY is a commandment and not a function for the 50G.

    You cannot use DOT in a function, you maybe wrote a program

    in RPL

    '--> x, y   '  x y DOT  XY ABS ABS * / ACOS   ' ""DOTHAN"STO

    [3.0] [0.3] DOTAN
    back 90 degrees

    I never use the algebraic mode but I guess it's the same thing with a program...

  • Getting a string of an agent customized by groovy

    I have a number of custom scripts agent and I can retrieve values using the query function:

    def qryService = server.get ("QueryService")

    qryStatement = qryService.createStatement ("metrics from table where monitoredHost.name = servername spanning from date time time_span")

    metricValue = avg (qryService.executeStatement (qryStatement))

    I can get the digital values appearing as ObservedValues in the script if editor I come down on the Forum, but I was not able to get the string values that are listed without comment by "ObservedValue".  The avg() statement above won't work of course for a string, but take it from me either Gets an empty container ([{} {}] or something that I have not been able to analyze (I'm a sysadmin, my JAVA and groovy is limited).)  I tried to use topologyobject instead of QueryService but I did not have what I wanted.

    I would like suggestions.

    Right you are, that works.

  • Problems with porting boost::regex when ranging from CS6 to CC2014 using Xcode

    I have a job in CS6 project which uses the framework boost::regex I have porting problems in CC2014.

    I wore this project using Dolly to create a new project, and then face the old files source overall, finally update the output of various dated calls to API InDesign that appeared when I compiled. For the use of regular expressions, I added the debug and release builds of the boost_regex.framework to the respective targets.

    Now, for the version new projects of CC2014 debug builds with happiness. But when I switch to the Release version I get some errors from the linker. They all have something like:

    Undefined symbols for x86_64 architecture:

    'boost::re_detail::get_mem_block()', referenced from:

    Boost::re_details:perl_matcher < __gnu_cxx::__normal_iterator < const char *, std::string >, std::allocator < boost::sub_match < __gnu_cxx::__normal_iterator < const char *, std::string > > >, < char, < char > boost::cpp_regex_traits > boost::regex:regex_traits >: find_imp() in SbRegex.o

    etc.

    I did a bit of reading through the impetus of header files. The strange thing is that the 'get_mem_block()' seems to be set for option pre processor BOOST_REGEX_NON_RECURSIVE, while in the project contains parameters for BOOST_PREPROCESSOR_DEFINITIONS BOOST_REGEX_RECURSIVE. These two parameters are mutually exclusive, and it is logical to preprocessor that blocks with both cases, defined both.

    This recursive option is used to control the use of memory when processing a regular expression, then see a call get_mem_block() (other errors of link imply a call to put_mem_block) somehow made sense being called that look like something to do with memory.

    I'm trying to understand why the debug builds, but Release version fails. This problem sound familiar to anyone? Anyone have any suggestions to try to fix it?

    Figured out how to build the project when you add the framework for regular expression of thrust.

    The key is the optimization level. When Dolly creates a project it defines the level of optimization for the Release version of "-O3". When you use boost::regex, you can only link correctly if you use the O0 and O1 optimization levels. Highest and link errors I saw appear.

    For the Release version, so I put in the Release_Cocoa64 build parameters 'Optimization level' to ' Fast [-O, O1] ' and it compiles.

  • invalid number of arguments

    I get the error while executing the following query.

    to find the max (two date columns)
     SELECT                 
             max(print_date,inv_date)
              
     FROM Temp;
    
         

    Hello

    Daniel wrote:
    I get the error while executing the following query.

    The error message really means what he says.
    For more information on all of the built-in functions, such as the number and types of arguments, see the Manual of the SQL language.

    to find the max (two date columns)

    SELECT
    max(print_date,inv_date)
    
    FROM Temp;
    

    MAX takes a single argument. (Most of the aggregate functions take one argument).
    You probably want the GREATER function, no MAX.

  • I want to convert the double data type to string type

    I want to convert the double data type to string, have idea about that

    Hello

    Use f

    FN: String (ARG) returns the string value of the argument. The argument can be a number, boolean, or node-set element

    Example: string (314)
    Result: "314".

    http://w3schools.com/XPath/xpath_functions.asp#string

    See you soon,.
    Vlad

Maybe you are looking for

  • Tecra S3 - Installation new WXP

    Hello together, Suppose a lot more should have this problem when they want to install new WXP. OK WXP Pro original CD with nLite/iso maker for the integration of the SATA/raid drivers to the fact of having NO floppy. Fact without problems! Booting fr

  • Error code: code 80072EE2

    When my computer trys to update, it used. When I study, it gives me the error code: code 80072EE2

  • Jedi outcast works on vista 64-bit

    I would like to install this game on my system, but I do know not true if it would work with it or not. the drive works under 98/2000/XP

  • Volume control icon disappeared

    My office is running vista and a few days ago the icon in the notification area white volume control has disappeared. When I go into the properties of the taskbar to show once again, the volume option is grayed out. Can anyone suggest a way to recove

  • Distribute the data file with the cod file?

    Hi all My application runs from a file of database on camera flash memory.  While the application can transfer data from my server to complete the database, the first download is quite large and takes a long time to run (I'm working on it). It occurr