`

Using Back References with String replaceAll method

阅读更多

from: http://blog.peterdelahunty.com/2008/08/using-back-references-with-string.html

 

This is small problem i was facing the other day and couldn't find much information about it on the web so thought i would blog about it.

The problem is how to use back references in Java regular expressions.

The problem is this. Say i have a String like so

"orderM 8orderA 3orderX 2NoReturn "

and i want to turn it into a String like so:

"order M#8 order A#3 orderX #2 NoReturn "

i can do this:

String test = "orderM 8orderA 3orderX 2NoReturn ";

String replaced = test.replaceAll ("([A-Z])([0-9])", " $1#$2 ");


What happens here is:

  1. first create two regular expression for matching all capital letters [A-Z] and all single digits [0-9]
  2. Next i then put each of these in a group. using ( ) brackets. The grouping means that the match is remembered and can be referenced by the replace string.
  3. In the replace string i can then reference the matches via the $n notation where n = the number of the group.


So what happens is: The regular expression processor moves along the string looking for cases of a capital letter next to a digit . When it find them it stores the capital letter in a group 1 and the digit in group 2.

So i want to replace the original match with another string i can.

Also note. The whole expression is automatically added to an implicit group zero 0 that is a group of the whole expression.

String replaced = test.replaceAll ("([A-Z])([0-9])", " '$0' ");

will give

order 'M8' order 'A3' order 'X2' NoReturn

IMPORTANT NOTE:

The javadoc says that you reference back references with '\n' (were n = number) but that is not true. That does not work you need to use '$n'. The javadoc is wrong and needs to be updated.

Pattern javadoc

Hope this helps :)

 

附上将串中a后一字母大写的正则:

String input = "abcadafghat";

String regex = "a(\\w)";
Matcher m = Pattern.compile(regex).matcher(input);
while (m.find()) {
    String temp = m.group();
    String uppercase;
    uppercase = temp.replaceAll("a(\\w)", "$1").toUpperCase();
    input = input.replace(temp, "a" + uppercase);
}

System.out.println(input);
 
分享到:
评论

相关推荐

    Using External References in Algorithms Compliant with the TMS320 algorithm standard.pdf

    本文将基于“Using External References in Algorithms Compliant with the TMS320 algorithm standard.pdf”这一应用报告,深入探讨如何在遵循TMS320 DSP算法标准的算法中引用外部实现的功能。 ### 引言:外部功能...

    Getting started with Spring Framework: covers Spring 5(epub)

    Spring Data MongoDB- Messaging, emailing and caching support- Spring Web MVC- Developing RESTful web services using Spring Web MVC- Functional programming using lambdas and method references-...

    Guide to Data Structures_A Concise Introduction Using Java-Springer(2017).pdf

    After an overview of preliminary concepts, this text introduces stacks and queues using arrays along with a discussion of array-based lists. This is followed by an introduction to linked lists and the...

    Pattern Recognition with Neural Networks in C++

    4.3 Training with Back Propagation 4.3.1 Back Propagation in C++ 4.4 A Primitive Example 4.5 Training Strategies and Avoiding Local Minima 4.6 Variations on Gradient Descent 4.6.1 Block ...

    servlet2.4doc

    The default behavior of this method is to return addHeader(String name, String value) on the wrapped response object. addHeader(String, String) - Method in interface javax.servlet....

    references.zip

    references/detection/engine.py , references/detection/utils.py 和 references/ detection/transforms.py

    Radar Systems Analysis and Design Using MatLab

    is quoted with permission, and sources are indicated. A wide variety of references are listed. Reasonable efforts have been made to publish reliable data and information, but the author and the ...

    Invent Your Own Computer Games with Python (2008).pdf

    The isalpha() String Method x The isupper() and islower() String Methods x Cryptanalysis x Brute Force x Chapter 10 - Reversi x How to Play Reversi x Source Code x The bool() Function x The random...

    Scientific Computing with Python 3

    Olivier Verdier began using Python for scientific computing back in 2007 and received a PhD in mathematics from Lund University in 2009. He has held post-doctoral positions in Cologne, Trondheim, ...

    hibernate4.3.5references chm文档

    hibernate4.3.5references chm文档

    CSharp 3.0 With the .NET Framework 3.5 Unleashed(english)

    - **Delegates**: Delegates are references to methods with a particular parameter list and return type. They are used for event handling. - **Events**: Events allow objects to notify other objects of ...

    Find Reference 2

    You can use this to redirect all references to TextureA (using TextureA) to TextureB, the same applied for shader, materials, mesh... Beware that replace references is very powerful yet dangerous ...

    Asset Cleaner PRO - Clean - Find References

    Feature 1 - Project Cleaner: 1、Actions for unused files 2、Enhanced Project View Feature 2 - Find References: 1、Find references, usages, relationships easily in ...2、Explore usages & references

    Python库 | wagtail_references-0.0.2.tar.gz

    《Python库 wagtail_references-0.0.2详解》 在Python编程领域,库的使用是提高开发效率和代码质量的重要手段。今天我们要探讨的是一个名为`wagtail_references`的Python库,版本号为0.0.2,它封装了一些特定的功能...

    Python Cookbook, 2nd Edition

    Using the Code from This Book Audience Organization Further Reading Conventions Used in This Book How to Contact Us Safari® Enabled Acknowledgments Chapter 1. Text Introduction ...

    vision-references.zip

    《torch.vision.references.detection深度解析》 在Python的机器学习领域,PyTorch是一个备受推崇的框架,它以其灵活性和高效性深受开发者喜爱。在PyTorch的生态系统中,torch.vision模块提供了图像处理和计算机...

    Graphics and GUIs with matlab 3, third edition

    Graphics and GUIs with matlab, third edition CONTENTS 1 INTRODUCTION 1.1 OVERVIEW 1.2 ORGANIZATION OF THIS BOOK 1.3 TERMINOLOGY AND THE MATLAB PROGRAMMING LANGUAGE 1.3.1 Getting Started 1.3.2 Getting ...

Global site tag (gtag.js) - Google Analytics