请求协助编写正则表达式:从Jar/War包中提取版本号
mvn deploy-file Got it, let’s work through this together—extracting version strings from legacy JAR/WAR filenames for mvn deploy-file trips up a lot of folks, so I’m glad you asked. First, let’s start with the most common filename patterns you’ll encounter, then build regex that handles them, and finally tie it into your Maven deploy command.
Step 1: Common JAR/WAR Filename Patterns
Legacy projects usually follow one of these naming conventions (adjust based on your actual files):
artifact-id-1.2.3.jarartifact-id-1.2.3-SNAPSHOT.warartifact-id-legacy-2.0.0.RELEASE.jarartifact-id-3.1.0-beta.1.war
Step 2: Regex to Extract the Version
Here’s a flexible regex that handles most standard version formats (including pre-release tags like SNAPSHOT, beta, RELEASE):
(?<=-\d)[\d.]+(?:-[A-Za-z0-9]+)?
Let’s break this down so you can tweak it if needed:
(?<=-\d): Positive lookbehind to make sure we’re starting right after a hyphen followed by a digit (avoids matching parts of the artifact ID)[\d.]+: Matches one or more digits or dots (covers core version numbers like1.2,3.1.4,2024.05)(?:-[A-Za-z0-9]+)?: Optional non-capturing group for pre-release tags (like-SNAPSHOT,-beta.1,-RELEASE)
If your versions have underscores or other special characters, just add them to the character class—for example, [\d._]+ to support underscores.
Step 3: Extracting the Version in the Command Line
Let’s say you have a file named my-legacy-app-2.1.0-SNAPSHOT.jar. Here’s how to pull the version using common tools:
Using grep (Linux/macOS)
VERSION=$(echo "my-legacy-app-2.1.0-SNAPSHOT.jar" | grep -oP '(?<=-\d)[\d.]+(?:-[A-Za-z0-9]+)?') echo $VERSION # Outputs: 2.1.0-SNAPSHOT
Using sed
VERSION=$(echo "my-legacy-app-2.1.0-SNAPSHOT.jar" | sed -E 's/.*-(\d[\d.]+(?:-[A-Za-z0-9]+)?)\.(jar|war)/\1/') echo $VERSION # Outputs: 2.1.0-SNAPSHOT
Step 4: Tie It to mvn deploy-file
Now plug this into your Maven deploy command. Let’s assume you have variables for artifact ID, group ID, and the file path:
FILE_PATH="./my-legacy-app-2.1.0-SNAPSHOT.jar" ARTIFACT_ID="my-legacy-app" GROUP_ID="com.mycompany.legacy" VERSION=$(echo $FILE_PATH | grep -oP '(?<=-\d)[\d.]+(?:-[A-Za-z0-9]+)?') mvn deploy-file \ -Dfile=$FILE_PATH \ -DgroupId=$GROUP_ID \ -DartifactId=$ARTIFACT_ID \ -Dversion=$VERSION \ -Dpackaging=jar \ -DrepositoryId=nexus-repo \ -Durl=https://your-nexus-url/repository/releases/
Handling Edge Cases
If your filenames are non-standard (e.g., my_app_v1.2.3.jar or 1.2.3-my-app.jar), just adjust the regex. For example:
- If versions start with a
v, use:v[\d.]+(?:-[A-Za-z0-9]+)? - If the version is at the start of the filename, use:
^[\d.]+(?:-[A-Za-z0-9]+)?
If you share a specific example of your JAR/WAR filenames, I can refine this even more!
内容的提问来源于stack exchange,提问作者Daniel Ferreira Castro

