찾다
Javajava지도 시간Regex를 사용하여 따옴표 안의 공백을 무시하면서 공백을 사용하여 문자열을 분할하는 방법은 무엇입니까?

How to Split a String Using Spaces While Ignoring Spaces Within Quotes Using Regex?

공백을 사용하여 문자열을 분할하는 정규식

문자열 작업을 할 때 분석이나 처리를 위해 문자열을 개별 단어로 분할해야 하는 경우가 많습니다. 그러나 인용된 텍스트 내의 공백(예: "이것은 문자열입니다.")은 구분 기호로 간주되어서는 안 됩니다. 정규식(Regex)은 이러한 복잡한 분할 작업을 처리하는 강력한 방법을 제공합니다.

질문:

둘러싸인 공백을 무시하고 공백을 사용하여 문자열을 분할하는 Regex 표현식을 만듭니다. 싱글 또는 더블로 quote.

예:

입력: "'정규 표현식'이 항목과 일치할 때 "강조 표시될" 문자열입니다."

원함 출력:

This
is
a
string
that
will be
highlighted
when
your
regular expression
matches
something.

답변:

제공된 표현식 (?!")이 올바르게 분할되지 않지만 포괄적인 Regex 표현식은 다음과 같이 공식화될 수 있습니다.

이 표현은 두 가지 유형을 효과적으로 포착합니다. 요소:

  • 따옴표가 없는 단어: [^s"']는 공백이나 따옴표가 없는 일련의 문자와 일치합니다.
  • 인용 텍스트:

    • /"([^"]*)"/ 일치 따옴표를 제외한 큰따옴표 텍스트.
    • /'([^']*)'/는 따옴표를 제외하고 작은따옴표 텍스트와 유사하게 일치합니다.

Java 구현:

다음 Java 코드는 이 Regex를 다음에 적용하는 방법을 보여줍니다. 문자열 분할:

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class RegexSplitter {

    public static void main(String[] args) {
        String subjectString = "This is a string that \"will be\" highlighted when your 'regular expression' matches something.";

        // Pattern that matches unquoted words, quoted texts, and the capturing groups
        Pattern regex = Pattern.compile("[^\s\"']+|\"([^\"]*)\"|'([^']*)'");
        Matcher regexMatcher = regex.matcher(subjectString);

        // List to store the split words
        List<string> matchList = new ArrayList();

        while (regexMatcher.find()) {
            // Check for capturing groups to exclude quotes
            if (regexMatcher.group(1) != null) {
                // Add double-quoted string without the quotes
                matchList.add(regexMatcher.group(1));
            } else if (regexMatcher.group(2) != null) {
                // Add single-quoted string without the quotes
                matchList.add(regexMatcher.group(2));
            } else {
                // Add unquoted word
                matchList.add(regexMatcher.group());
            }
        }

        // Display the split words
        for (String word : matchList) {
            System.out.println(word);
        }
    }
}</string>

출력:

This
is
a
string
that
will be
highlighted
when
your
regular expression
matches
something

이 향상된 토론은 문제를 명확하게 하고 자세한 설명과 함께 보다 정확하고 포괄적인 Regex 표현식을 제공합니다. 사용법을 보여주기 위한 Java 구현입니다.

위 내용은 Regex를 사용하여 따옴표 안의 공백을 무시하면서 공백을 사용하여 문자열을 분할하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.
Java 플랫폼은 어떻게 독립적입니까?Java 플랫폼은 어떻게 독립적입니까?May 09, 2025 am 12:11 AM

Java는 JVM (Java Virtual Machines) 및 바이트 코드에 의존하는 "Write Once, Everywhere 어디에서나 Run Everywhere"디자인 철학으로 인해 플랫폼 독립적입니다. 1) Java Code는 JVM에 의해 해석되거나 로컬로 계산 된 바이트 코드로 컴파일됩니다. 2) 라이브러리 의존성, 성능 차이 및 환경 구성에주의하십시오. 3) 표준 라이브러리를 사용하여 크로스 플랫폼 테스트 및 버전 관리가 플랫폼 독립성을 보장하기위한 모범 사례입니다.

Java의 플랫폼 독립성에 대한 진실 : 정말 간단합니까?Java의 플랫폼 독립성에 대한 진실 : 정말 간단합니까?May 09, 2025 am 12:10 AM

java'splatformincceldenceisisnotsimple; itinvolvescomplex

Java 플랫폼 독립성 : 웹 응용 프로그램의 장점Java 플랫폼 독립성 : 웹 응용 프로그램의 장점May 09, 2025 am 12:08 AM

Java'SplatformIndenceBenefitsWebApplicationScodetorUnonySystemwithajvm, simplifyingDeploymentandScaling.Itenables : 1) EasyDeploymentAcrossDifferentservers, 2) SeamlessScalingAcrossCloudPlatforms, 3))

JVM 설명 : Java Virtual Machine에 대한 포괄적 인 가이드JVM 설명 : Java Virtual Machine에 대한 포괄적 인 가이드May 09, 2025 am 12:04 AM

thejvmistheruntimeenvironmenmentforexecutingjavabytecode, Crucialforjava의 "WriteOnce, runanywhere"capability.itmanagesmemory, executesThreads, andensuressecurity, makingestement ofjavadeveloperStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandStandSmetsmentsMemory

Java의 주요 기능 : 왜 최고의 프로그래밍 언어로 남아 있는지Java의 주요 기능 : 왜 최고의 프로그래밍 언어로 남아 있는지May 09, 2025 am 12:04 AM

javaremainsatopchoicefordevelopersdueToitsplatformindence, 객체 지향 데 디자인, 강력한, 자동 메모리 관리 및 compehensiveStandardlibrary

Java 플랫폼 독립성 : 개발자에게 무엇을 의미합니까?Java 플랫폼 독립성 : 개발자에게 무엇을 의미합니까?May 08, 2025 am 12:27 AM

Java'splatforminceldenceMeansdeveloperscanwriteCodeOnceAndrunitonAnyDevicewithoutRecompiling.thisiSocievedTheRoughthejavirtualMachine (JVM), thisTecodeIntomachine-specificinstructions, hallyslatslatsplatforms.howev

첫 번째 사용을 위해 JVM을 설정하는 방법은 무엇입니까?첫 번째 사용을 위해 JVM을 설정하는 방법은 무엇입니까?May 08, 2025 am 12:21 AM

JVM을 설정하려면 다음 단계를 따라야합니다. 1) JDK 다운로드 및 설치, 2) 환경 변수 설정, 3) 설치 확인, 4) IDE 설정, 5) 러너 프로그램 테스트. JVM을 설정하는 것은 단순히 작동하는 것이 아니라 메모리 할당, 쓰레기 수집, 성능 튜닝 및 오류 처리를 최적화하여 최적의 작동을 보장하는 것도 포함됩니다.

내 제품의 Java 플랫폼 독립성을 어떻게 확인할 수 있습니까?내 제품의 Java 플랫폼 독립성을 어떻게 확인할 수 있습니까?May 08, 2025 am 12:12 AM

ToensureJavaplatform Independence, followthesesteps : 1) CompileIndrunyourApplicationOnMultiplePlatformsUsingDifferentOnsandjvMversions.2) Utilizeci/CDPIPELINES LICKINSORTIBACTIONSFORAUTOMATES-PLATFORMTESTING

See all articles

핫 AI 도구

Undresser.AI Undress

Undresser.AI Undress

사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover

AI Clothes Remover

사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool

Undress AI Tool

무료로 이미지를 벗다

Clothoff.io

Clothoff.io

AI 옷 제거제

Video Face Swap

Video Face Swap

완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

뜨거운 도구

SublimeText3 중국어 버전

SublimeText3 중국어 버전

중국어 버전, 사용하기 매우 쉽습니다.

WebStorm Mac 버전

WebStorm Mac 버전

유용한 JavaScript 개발 도구

에디트플러스 중국어 크랙 버전

에디트플러스 중국어 크랙 버전

작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음

DVWA

DVWA

DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

스튜디오 13.0.1 보내기

스튜디오 13.0.1 보내기

강력한 PHP 통합 개발 환경